Neste Caminho de Aprendizado Conectado, criaremos uma cadeia que ilustra como converter um arquivo XML em CSV. Além disso, exploraremos como comparar conjuntos de dados para isolar diferenças.
| Objetivo principal de aprendizado | O conector XML |
| Objetivos secundários de aprendizado | Filtros inteligentes de transformação tabular, alteração de delimitador e comandos de consulta avançada |
| Pré-requisitos | Configurar a conexão do conector XML |
| Modelo de suporte | CLP | Acesso a dados XML |
Etapa 1: Criar uma corrente
- Add a new Chain, and name the Chain: CLP | Accessing XML Data.
- Crie duas variáveis de cadeia da seguinte forma:
- Under Chain Variables, click the plus sign (+) twice.
- Use os seguintes nomes e valores para as variáveis:
- Variável XML
- Name: cv-XML-Employee
- Value: https://cs-sftp-training-bucket.s3.amazonaws.com/cs-training/transformation-qs/employees.xml
- Variável CSV
- Name: cv-CSV-Employee
- Value: https://cs-sftp-training-bucket.s3.amazonaws.com/cs-training/transformation-qs/employee_detail.csv
- Variável XML
- Salvar a corrente
Etapa 2: Recuperar dados no formato CSV
Use o Conector HTTP para recuperar dados relacionados ao número de funcionários no formato CSV. Em etapas posteriores, recuperaremos informações semelhantes sobre o número de funcionários no formato XML e, em seguida, compararemos os conjuntos de dados para identificar as diferenças.
- Add a GET Command from the HTTP Connector to the Start node.
-
Configure o comando usando os seguintes valores:
Nome GET - Headcount no formato CSV Nome do usuário <leave blank> Senha <leave blank> Certificado CA <leave blank> Certificado <leave blank> Chave privada do certificado <leave blank> Mostrar resposta Verificado URL cv-CSV-Employee Chain Variable Cadeia de consulta <leave blank> Tipo de conteúdo text/csv Resposta <leave blank> - Salvar o comando
Etapa 3: Recuperar dados no formato XML
Use o Conector HTTP para recuperar dados relacionados ao número de funcionários no formato XML. Conforme observado na etapa 2, em uma etapa posterior, compararemos o conjunto de dados XML com o conjunto de dados CSV para identificar as diferenças.
- Add a GET Command from the HTTP Connector to the Chain.
- Connect the Start Node (GET - Headcount in CSV Format) to the GET Command.
-
Configure o comando usando os seguintes valores:
Nome GET - Headcount no formato XML Nome do usuário <leave blank> Senha <leave blank> Certificado CA <leave blank> Certificado <leave blank> Chave privada do certificado <leave blank> Mostrar resposta Verificado URL cv-XML-Employee Chain Variable Cadeia de consulta <leave blank> Tipo de conteúdo application/xml Resposta <leave blank> - Salvar o comando
Etapa 4: converter o arquivo XML em delimitado
Use o XML Connector para converter os dados XML em um formato CSV, o que nos permite aproveitar comandos posteriores na cadeia que esperam dados em um formato delimitado.
- Add an Element List to CSV Command from the XML Connector to the Chain.
- Connect the GET - Headcount in XML Format Command to the Element List to CSV Command.
- Configure o comando usando os seguintes valores:
- For the Input File parameter, select the Response Output from the GET - Headcount in XML Format Command.
- Leave the Input Text parameter blank.
- For the Path to root parameter, enter the following envelope information:
/employee_data/employee - Mark the Preview Result parameter checkbox.
-
For the Columns section, click the Add button 12 times.
For each of the added columns, enter the name of the field from the data record previewed in the previous step in both the Column Name and XPath fields.
Example: emp_id⚠️ O campo XPath diferencia maiúsculas de minúsculas e deve corresponder à caixa do envelope.
- Para o parâmetro Multi-value Delimiter (Delimitador de vários valores), insira um pipe (|).
- Salvar o comando
- Publique, execute e execute a cadeia.
-
Review the Log tab of the Element List to CSV - All Employees Command node and confirm a list of employees is displayed.
⚠️ Não pule a execução e a revisão dos resultados dessa etapa, pois uma cópia desse comando será criada na cadeia e quaisquer erros precisarão ser corrigidos posteriormente em várias instâncias do comando.
Etapa 5: Alterar o XML convertido de delimitado por tabulação para delimitado por vírgula
Use o Conector de transformação tabular para converter a saída gerada pela conversão de XML de um formato delimitado por tabulação para um formato delimitado por vírgula.
- Add a Change Delimiter Command from the Tabular Transformation Connector to the Chain.
- Connect the Element List to CSV - All Employees Command to the Change Delimiter Command.
- Configure o comando usando os seguintes valores:
- Name: Change Delimiter - All Employees
- Input File: Converted File Output from the Element List to CSV - All Employees Command
- Input Delimiter: \t
- Output Delimiter: , (comma)
- Salvar o comando
Etapa 6: comparar os conjuntos de dados CSV e XML para identificar as diferenças
Use Advanced Query to systematically identify differences between the XML and native CSV data sets. Neste exemplo, identifique todos os registros no conjunto de dados XML que sejam diferentes ou estejam faltando no conjunto de dados CSV. Quaisquer registros adicionais encontrados no conjunto de dados CSV que não estejam no conjunto de dados XML não serão identificados por este exercício.
- Add an Advanced Query Command from the Tabular Transformation Connector to the Chain.
- Connect the Change Delimiter - All Employees Command to the Advanced Query Command.
- Name the Command: Advanced Query - All Employees.
- In the Tables section, click the Add button to add a second tab.
- Para a primeira tabela:
- Specify the CSV Result Output from the Change Delimiter - All Employees Command.
- Specify XML as the Table Name.
- Para a segunda tabela:
- Specify the Response Output from the GET - Headcount in CSV Format Command.
Specify CSV as the Table Name. - In the Query parameter, enter the following:
Select * from XML EXCEPT Select * from CSV - In the Input Delimiter and Output Delimiter fields, specify Comma.
- Check the Preview Results option.
- Specify the Response Output from the GET - Headcount in CSV Format Command.
- Para a primeira tabela:
- Salvar o comando
- Publish, Execute, and Run the Chain.
-
Review the Log tab of the Advanced Query - All Employees Command node and confirm the employee IDs match the below for the records returned by the query.
ID do funcionário 01-6875791 10-4199621 38-3932553 63-0417180 78-3600453 85-6818050 97-2828467
Etapa 7: Adicionar um grupo de comandos
Adicione um grupo de comandos à cadeia para organizar melhor os comandos. Embora essa etapa seja necessária em termos deste exercício, ela não é um requisito técnico para a Chain. Esta etapa serve apenas para ilustrar a capacidade de organizar os nós de uma cadeia.
- Add a Command Group to the Chain.
- Connect the GET - Headcount in XML Format Command to the In section of the Command Group.
- Click the Command Group and then select the dropper icon to change the Command color to red.
- Name the Group: Active Employees.
Etapa 8: Filtrar dados CSV somente para funcionários ativos
Use um Filtro Inteligente para manter apenas os registros de funcionários em que o funcionário está ativo. Ao definir o filtro, presumimos que o fato de o campo terminado (denominado) estar em branco indica que um funcionário está ativo.
- Add a Smart Filter Rows Command from the Tabular Transformation Connector to the Chain.
- Connect the Group Start from the Command Group to the Smart Filter Command.
- Configure o comando usando os seguintes valores:
- Name the Command: Smart Filter Rows - CSV Data - Active Employees.
- For the Input file parameter, select the Response Output from the GET - Headcount in CSV Format Command.
- Leave the Output file parameter blank.
- Specify Comma as the Delimiter.
- In the Filters section complete the following steps:
- Click the Add button on the Text filters.
- In the Column name parameter, enter termed.
- Check the Case Insensitive option.
- From the Condition dropdown, select Equals.
- In the Compare Text parameter, enter true.
- Check the Not option.
- Leave the Trim checkbox unchecked.
This filter will now identify any record where the field "termed" does not contain a value of true (that is, it contains "false" or is blank).
- Leave the Preview Result option marked.
- The Inverse option allows the Smart Filter to either keep (checked) or remove (unchecked) all rows that match the filter criteria. Neste exercício, queremos manter todas as linhas em que o campo "termed" tenha um valor verdadeiro ou em branco.
To achieve this, mark (check) the Inverse checkbox. - Salvar o comando
Etapa 8: Filtrar dados CSV somente para funcionários ativos
Use um Filtro Inteligente para manter apenas os registros de funcionários em que o funcionário está ativo. Ao definir o filtro, presumimos que o fato de o campo terminado ("termed") estar em branco indica que um funcionário está ativo.
- Add a Smart Filter Rows Command from the Tabular Transformation Connector to the Chain.
- Connect the Group Start from the Command Group to the Smart Filter Command.
- Configure o comando usando os seguintes valores:
- Name the Command: Smart Filter Rows - CSV Data - Active Employees.
- For Input file, select the Response Output from the GET - Headcount in CSV Format Command.
- Leave the Output file parameter blank.
- Specify Comma as the Delimiter.
- In the Filters section,
- Click the Add button on the Text filters.
- In the Column name parameter, enter termed.
- Check the Case Insensitive option.
- From the Condition dropdown, select Equals.
- In the Compare Text parameter, enter true.
- Check the Not option.
- Leave the Trim checkbox unchecked.
This filter will now identify any record where the field "termed" does not contain a value of true (that is, it contains "false" or is blank).
- Leave the Preview Result checkbox marked (checked).
- The Inverse option allows the Smart Filter to either keep (checked) or remove (unchecked) all rows that match the filter criteria. Neste exercício, queremos manter todas as linhas em que o campo termed tenha o valor true ou blank. To achieve this, mark (check) the Inverse checkbox.
- Salvar o comando
Etapa 9: Filtrar dados XML durante a conversão para delimitado
Nesta etapa, filtramos os dados XML durante a conversão para um formato delimitado para identificar somente os funcionários ativos. Esse conjunto de dados será posteriormente comparado com o conjunto de dados CSV filtrado para identificar diferenças.
- Copy the Element List to CSV - All Employees Command.
- Connect the Group Start from the Command Group to the Element List to CSV - All Employees (Copy) Command.
- Edit the Command, naming it: Element List to CSV - Active Employees.
- In the "Path to root" parameter, enter the following.
/employee_data/employee[termed!='true']
This will now identify any record where the field "termed" does not contain a value of true (that is, it contains "false" or is blank). - Salvar o comando
Etapa 10: Alterar os dados XML filtrados para delimitados por vírgula
Assim como na lista completa de funcionários, a lista de funcionários ativos filtrada que foi convertida de XML para delimitada por tabulação precisa ser convertida para delimitada por vírgula.
- Copy the Change Delimiter - All Employees Command.
- Connect the Element List to CSV - Active Employees Command to the Element Change Delimiter - All Employees (Copy) Command.
- Configure o comando usando os seguintes valores.
- Name: Change Delimiter - Active Employees.
- Modify the Input file parameter to use the Converted File Output from the Element List to CSV - Active Employees Command.
- Salvar o comando
Etapa 11: Verificação de diferenças com funcionários ativos
Assim como na lista completa de funcionários, a lista de funcionários ativos filtrada que foi convertida de XML para delimitada por tabulação precisa ser convertida para delimitada por vírgula.
- Copy the Advanced Query - All Employees Command.
- Connect the Out of the Command Group to the Advanced Query - All Employees (Copy) Command. Ao conectar o comando Advanced Query - All Employees ao Group Out, você garante que tudo o que estiver conectado ao Group Start será concluído antes que a cadeia avance para os comandos no Group Out.
- Configure o comando usando os seguintes valores:
- Name: Advanced Query - Active Employees.
-
In the Tables section, modify the File parameter for both tables using the following values:
Tabela Arquivo XML CSV Result Output from the Change Delimiter - Active Employees Command CSV Smart Filter Row Output from the Smart Filter Rows - Active Only, CSV Data Command
- Salvar o comando
Etapa 12: Teste o exercício
Agora que a cadeia está concluída, teste o resultado.
- Publish the Chain.
- Click Execute and then select Run Chain.
- Once the Chain has completed its run, click the Advanced Query - Active Employees node.
- On the Outputs tab, confirm that 4 records were output.
-
Clique na guia Logs e confirme se os IDs dos funcionários correspondem aos registros retornados pela consulta.
ID do funcionário 01-6875791 63-0417180 78-3600453 85-6818050
To learn more about data transformation using Chains, check out the Connected Learning Paths - Transformation Introduction!