En esta Ruta de aprendizaje conectada, crearemos una Cadena que ilustra cómo convertir un archivo XML a CSV. Además, exploraremos cómo comparar conjuntos de datos para aislar las diferencias.
| Objetivo principal de aprendizaje | El conector XML |
| Objetivos de aprendizaje secundarios | Transformación tabular Filtros inteligentes, cambio de Delimitador y comandos de consulta avanzados. |
| Requisitos previos | Configura la Conexión del Conector XML |
| Plantilla de ayuda | CLP | Acceder a los datos XML |
Paso 1: Crea una Cadena
- Add a new Chain, and name the Chain: CLP | Accessing XML Data.
- Crea dos variables de Cadena como sigue:
- Under Chain Variables, click the plus sign (+) twice.
- Utiliza los siguientes nombres y valores para las variables:
- Variable XML
- Name: cv-XML-Employee
- Value: https://cs-sftp-training-bucket.s3.amazonaws.com/cs-training/transformation-qs/employees.xml
- Variable CSV
- Name: cv-CSV-Employee
- Value: https://cs-sftp-training-bucket.s3.amazonaws.com/cs-training/transformation-qs/employee_detail.csv
- Variable XML
- Guarda la cadena.
Etapa 2: Recuperar datos en formato CSV
Utiliza el conector HTTP para recuperar datos relacionados con el recuento en formato CSV. En etapas posteriores, recuperaremos información similar sobre los recuentos en formato XML y, a continuación, compararemos los conjuntos de datos para identificar las diferencias.
- Add a GET Command from the HTTP Connector to the Start node.
-
Configura el Comando utilizando los siguientes valores:
Nombre GET - Recuento en formato CSV Nombre de usuario <leave blank> Contraseña <leave blank> Certificado CA <leave blank> Certificado <leave blank> Certificado Clave Privada <leave blank> Mostrar respuesta Comprobado URL cv-CSV-Employee Chain Variable Cadena de consulta <leave blank> Tipo de contenido texto/csv Respuesta <leave blank> - Guarda el comando.
Etapa 3: Recuperar datos en formato XML
Utiliza el conector HTTP para recuperar datos relacionados con el recuento en formato XML. Como se indicó en la etapa 2, en una etapa posterior compararemos el conjunto de datos XML con el conjunto de datos CSV para identificar las diferencias.
- Add a GET Command from the HTTP Connector to the Chain.
- Connect the Start Node (GET - Headcount in CSV Format) to the GET Command.
-
Configura el Comando utilizando los siguientes valores:
Nombre GET - Recuento en formato XML Nombre de usuario <leave blank> Contraseña <leave blank> Certificado CA <leave blank> Certificado <leave blank> Certificado Clave Privada <leave blank> Mostrar respuesta Comprobado URL cv-XML-Employee Chain Variable Cadena de consulta <leave blank> Tipo de contenido aplicación/xml Respuesta <leave blank> - Guarda el comando.
Etapa 4: Convierte el archivo XML a Delimitado.
Utiliza el Conector XML para convertir los datos XML a un formato CSV que nos permita aprovechar comandos posteriores de la Cadena que esperan datos en un 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.
- Configura el Comando utilizando los siguientes 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⚠️ El campo XPath distingue entre mayúsculas y minúsculas y debe coincidir con el sobre.
- Para el parámetro Delimitador de valores múltiples, introduce un tubo (|).
- Guarda el comando.
- Publicar, Ejecutar y Ejecutar la cadena.
-
Review the Log tab of the Element List to CSV - All Employees Command node and confirm a list of employees is displayed.
⚠️ No te saltes la ejecución y revisión de resultados de este paso, ya que se creará una Copia de este Comando en la Cadena y, posteriormente, habría que corregir cualquier error en varias instancias del Comando.
Etapa 5: Cambiar el XML convertido de delimitado por pestañas a delimitado por comas.
Utiliza el conector de transformación tabular para convertir el resultado generado desde la conversión XML de un formato delimitado por pestañas a un formato delimitado por comas.
- 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.
- Configura el Comando utilizando los siguientes 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)
- Guarda el comando.
Etapa 6: Comparar los Conjuntos de datos CSV y XML para identificar las diferencias
Use Advanced Query to systematically identify differences between the XML and native CSV data sets. En este ejemplo, identifica todos los registros del conjunto de datos XML que sean diferentes o que falten del conjunto de datos CSV. Cualquier registro adicional encontrado en el conjunto de datos CSV que no esté en el conjunto de datos XML no se identificará con este ejercicio.
- 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 la primera tabla:
- Specify the CSV Result Output from the Change Delimiter - All Employees Command.
- Specify XML as the Table Name.
- Para la segunda tabla:
- 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 la primera tabla:
- Guarda el 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 de empleado 01-6875791 10-4199621 38-3932553 63-0417180 78-3600453 85-6818050 97-2828467
Etapa 7: Añadir un grupo de comandos
Añadir un grupo de comandos a la cadena para organizar mejor los comandos. Aunque esta etapa es necesaria en lo que respecta a este ejercicio, no es un requisito técnico para la Cadena. Esta etapa sólo sirve para ilustrar la capacidad de organización de los nodos de una Cadena.
- 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 datos CSV solo para empleados activos
Utiliza un filtrado inteligente para conservar solo los registros de empleados en los que el empleado esté activo. Al definir el filtro, suponemos que el campo terminado (denominado) en blanco indica que un empleado está activo.
- 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.
- Configura el Comando utilizando los siguientes 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. En este ejercicio, queremos conservar todas las filas en las que el campo "denominado" tenga un valor de verdadero o en blanco.
To achieve this, mark (check) the Inverse checkbox. - Guarda el comando.
Etapa 8: Filtrar datos CSV solo para empleados activos
Utiliza un filtrado inteligente para conservar solo los registros de empleados en los que el empleado esté activo. Al definir el filtro, suponemos que el campo terminado ("terminado") está en blanco, lo que indica que un empleado está activo.
- 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.
- Configura el Comando utilizando los siguientes 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. En este ejercicio, queremos conservar todas las filas en las que el campo denominado tenga un valor de verdadero o esté en blanco. To achieve this, mark (check) the Inverse checkbox.
- Guarda el comando.
Etapa 9: Filtrar datos XML al convertir a Delimitado
En esta etapa, filtramos los datos XML al convertirlos a un formato delimitado para identificar solo a los empleados activos. Este conjunto de datos se comparará posteriormente con el conjunto de datos CSV filtrado para identificar las diferencias.
- 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). - Guarda el comando.
Etapa 10: Cambia los Datos XML filtrados a Delimitados por Comas.
Al igual que con la lista de empleados completa, la lista de empleados activos filtrada que se ha convertido de XML a delimitada por pestañas debe convertirse a delimitada por comas.
- 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.
- Configura el comando utilizando los siguientes 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.
- Guarda el comando.
Etapa 11: Comprobar las diferencias con los Empleados Activos
Al igual que con la lista de empleados completa, la lista de empleados activos filtrada que se ha convertido de XML a delimitada por pestañas debe convertirse a delimitada por comas.
- Copy the Advanced Query - All Employees Command.
- Connect the Out of the Command Group to the Advanced Query - All Employees (Copy) Command. Si conectas el comando Consulta avanzada - Todos los empleados al Grupo de salida, te aseguras de que todo lo que esté conectado al Grupo de salida termine antes de que la cadena avance hacia los comandos del Grupo de salida.
- Configura el Comando utilizando los siguientes valores:
- Name: Advanced Query - Active Employees.
-
In the Tables section, modify the File parameter for both tables using the following values:
Tabla Archivo XML|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
- Guarda el comando.
Etapa 12: Evaluar el ejercicio
Ahora que la Cadena está completa, evalúa el 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.
-
Haz clic en la pestaña Registros y confirma que los ID de los empleados coinciden con los de abajo para los registros devueltos por la consulta.
ID de empleado 01-6875791 63-0417180 78-3600453 85-6818050
To learn more about data transformation using Chains, check out the Connected Learning Paths - Transformation Introduction!