Saltar al contenido

Procesamiento de XML con Shell: Cómo actualizar un valor en un archivo XML en 5 minutos

Aprende a usar xmlstarlet para actualizar valores en archivos XML y manejar cargas XML complejas de manera eficiente en tus scripts de shell

Procesamiento de XML en Shell: Cómo actualizar valores en archivos XML
Foto de Shahadat Rahman en Unsplash

Si trabajas en TI o incluso si consideras TI como uno de tus principales pasatiempos, has escrito un script de shell en algún momento. Si también trabajas en el lado operativo del negocio, esta puede ser tu tarea diaria. Crear, mantener o actualizar el proceso existente.

Hoy en día, es más común interactuar con sistemas externos que utilizan cargas en archivos XML o incluso archivos de configuración escritos en este formato.

El script de shell nativo no proporciona una manera fácil de hacer eso ni bibliotecas de soporte para manejarlo como podemos en lenguajes de programación modernos como Python, Java o Go. Así que, probablemente te has encontrado escribiendo código para analizar este tipo de carga. Pero esta no es la única manera de hacerlo, y podemos (¡y debemos!) aprovechar las utilidades existentes para hacer este trabajo por nosotros.

xmlstarlet

No pude encontrar una mejor manera de explicar lo que hace xmlstarlet que la definición que los propietarios hacen en su repositorio de código fuente:

XMLStarlet es un conjunto de herramientas XML de línea de comandos que se puede usar para transformar,
consultar, validar y editar documentos y archivos XML usando un conjunto simple de comandos de shell
de manera similar a como se hace para archivos de texto plano usando grep/sed/awk/
tr/diff/patch.

Así que, xmlstarlet proporciona todo el poder para hacer cualquier cosa que puedas imaginar al tratar con XML de manera similar a como si fueran archivos de texto plano.

Instalación

El proceso de instalación de esta utilidad es bastante fácil y depende del sistema operativo que estés usando. Asumiré que la mayoría de los scripts de shell están dirigidos a una máquina Unix. Instalar esto es bastante fácil ya que la mayoría de los repositorios de paquetes tienen una versión de esta herramienta.

Así que, si estás usando un sistema basado en apt, necesitas ejecutar el comando:

sudo apt-get install xmlstarlet

Si estás usando otra plataforma, no te preocupes porque tienen versiones disponibles para todos los sistemas operativos y plataformas más utilizados, como puedes ver en el enlace a continuación:

Uso

Tan pronto como tengamos este software instalado, lo primero que haremos es lanzarlo para ver las opciones disponibles.

XMLStarlet Toolkit: Utilidades de línea de comandos para XML
Uso: D:DataDownloadsxmlstarlet-1.6.1-win32xmlstarlet-1.6.1xmlstarlet.exe [<opciones>] <comando> [<opciones-cmd>]
donde <comando> es uno de:
  ed    (o edit)      - Editar/Actualizar documento(s) XML
  sel   (o select)    - Seleccionar datos o consultar documento(s) XML (XPATH, etc)
  tr    (o transform) - Transformar documento(s) XML usando XSLT
  val   (o validate)  - Validar documento(s) XML (bien formado/DTD/XSD/RelaxNG)
  fo    (o format)    - Formatear documento(s) XML
  el    (o elements)  - Mostrar estructura de elementos del documento XML
  c14n  (o canonic)   - Canonicalización XML
  ls    (o list)      - Listar directorio como XML
  esc   (o escape)    - Escapar caracteres especiales XML
  unesc (o unescape)  - Desescapar caracteres especiales XML
  pyx   (o xmln)      - Convertir XML en formato PYX (basado en ESIS - ISO 8879)
  p2x   (o depyx)     - Convertir PYX en XML
<opciones> son:
  -q o --quiet        - sin salida de error
  --doc-namespace     - extraer enlaces de espacio de nombres del documento de entrada (por defecto)
  --no-doc-namespace  - no extraer enlaces de espacio de nombres del documento de entrada
  --version           - mostrar versión
  --help              - mostrar ayuda
Dondequiera que se mencione el nombre del archivo en la ayuda del comando, se asume
que se puede usar una URL en su lugar también.

Escribe: xmlstarlet <comando> --help <ENTER> para ayuda del comando

Así que lo primero que necesitamos decidir es qué comando necesitamos usar, y estos comandos están relacionados uno a uno con la acción que queremos realizar. Me centraré en los comandos principales en este post, pero como puedes ver, esto cubre desde seleccionar valores en un XML, actualizarlo o incluso validarlo.

Caso de uso 1: Seleccionar un valor.

Vamos a comenzar con el caso de uso más simple, intentar seleccionar un valor de un XML (file.xml) como este:

<root>
<object1 name="attribute_name">valor en XML</object1>
</root>

Así que, vamos a comenzar con el comando más simple:

./xmlstarlet  sel  -t -v "/root/object1"  ./file.xml

valor en XML

Esto proporciona el valor dentro del elemento object1, usando -t para definir una nueva plantilla y -v para especificar la sentencia value-of. Si ahora, quisiéramos obtener el valor del atributo, podemos hacerlo de manera muy similar al comando anterior:

./xmlstarlet  sel  -t -v "/root/object1/@name"  ./file.xml

attribute_name

Caso de uso 2: Actualizar valor.

Ahora, seguiremos el otro enfoque basado en el mismo archivo. Actualizaremos el valor del elemento object1 para establecer el texto «texto actualizado».

Para hacer eso, ejecutamos el siguiente comando:

./xmlstarlet ed -u "/root/object1" -v "texto actualizado" ./file.xml

<?xml version="1.0"?>
<root>
  <object1 name="attribute_name">texto actualizado</object1>
</root>

Resumen

xmlstarlet nos proporcionará todas las opciones para manejar algo tan complicado como lo es XML y realizar todas las tareas que puedas imaginar de manera simple sin necesidad de codificar tú mismo toda la lógica de análisis. Espero que seas un desarrollador más feliz desde ahora cuando necesites manejar un XML dentro de un script de shell.

Etiquetas:

Shell XML Processing: How To Update value in XML file in 5 Minutes

Learn how to use xmlstarlet to update value in XML file and handle complex XML payloads efficiently in your shell scripts

Shell XML Processing: How To Update value in XML file
Photo by Shahadat Rahman on Unsplash

If you work in IT or even if you think about IT as one of your main hobbies, you have been written a shell script at some point. If you also work on the business’s operation side, this can be your daily task. To create, maintain, or to upgrade the existing process.

Nowadays, it is more usual to interact with external systems that use payload in XML files or even configuration files written using this format.

Native shell script does not provide an easy way to do that or support libraries to handle that as we can in modern programming languages like Python, Java, or Go. So, probably you have found yourself writing code to parse this kind of payload. But this is not the only way to do that, and we can (and we should!) leverage existing utilities to do this job for us.

xmlstarlet

I could not find a better way to explain what xmlstarlet does than the definition the owners do in their source code repository:

XMLStarlet is a command line XML toolkit which can be used to transform,
query, validate, and edit XML documents and files using simple set of shell
commands in similar way it is done for plain text files using grep/sed/awk/
tr/diff/patch.

So, xmlstarlet provides all the power to do anything you can imagine when dealing with XML similarly, as this was plain text files.

Installation

The installation process for this utility is quite easy and depends on the operating system you are using. I will assume that most of the shell scripts are with a Unix machine target in mind. Installing this is quite easy as most of the package repositories have a version of this tool.

So, if you are using an apt-based system, you need to execute the command:

sudo apt-get install xmlstarlet

If you are using another platform, do not worry because they have available versions for all the most used operating systems and platforms, as you can see in the link below:

Usage

As soon as we have this software installed, the first thing we will do is launch it to see the options available.

XMLStarlet Toolkit: Command line utilities for XML
Usage: D:\Data\Downloads\xmlstarlet-1.6.1-win32\xmlstarlet-1.6.1\xmlstarlet.exe [<options>] <command> [<cmd-options>]
where <command> is one of:
  ed    (or edit)      - Edit/Update XML document(s)
  sel   (or select)    - Select data or query XML document(s) (XPATH, etc)
  tr    (or transform) - Transform XML document(s) using XSLT
  val   (or validate)  - Validate XML document(s) (well-formed/DTD/XSD/RelaxNG)
  fo    (or format)    - Format XML document(s)
  el    (or elements)  - Display element structure of XML document
  c14n  (or canonic)   - XML canonicalization
  ls    (or list)      - List directory as XML
  esc   (or escape)    - Escape special XML characters
  unesc (or unescape)  - Unescape special XML characters
  pyx   (or xmln)      - Convert XML into PYX format (based on ESIS - ISO 8879)
  p2x   (or depyx)     - Convert PYX into XML
<options> are:
  -q or --quiet        - no error output
  --doc-namespace      - extract namespace bindings from input doc (default)
  --no-doc-namespace   - don't extract namespace bindings from input doc
  --version            - show version
  --help               - show help
Wherever file name mentioned in command help it is assumed
that URL can be used instead as well.

Type: xmlstarlet <command> --help <ENTER> for command help

So the first thing we need to decide is which command we need to use, and these commands are one-to-one related to the action that we like to perform. I will focus on the main commands in this post, but as you can see, this covers from select values an XML, update it or even validate it.

Use case 1: Selecting a value.

We are going to start with the most simple use case try to select a value from an XML (file.xml) like this:

<root>
<object1 name="attribute_name">value in XML</object1>
</root>

So, we are going to start with the most simple command:

./xmlstarlet  sel  -t -v "/root/object1"  ./file.xml

value in XML

This provides the value inside the object1 element, using -t to define a new template and -v to specify the value-of sentence. If now, we would like to get the attribute value, we can do it pretty much similar to the previous command:

./xmlstarlet  sel  -t -v "/root/object1/@name"  ./file.xml

attribute_name

Use case 2: Updating value.

Now, we will follow the other approach based on the same file. We will update the value of the object1 element to set the text “updated text”.

To do that, we execute the following command:

./xmlstarlet ed -u "/root/object1" -v "updated text" ./file.xml

<?xml version="1.0"?>
<root>
  <object1 name="attribute_name">updated text</object1>
</root>

Summary

xmlstarlet will provide us all the options to manage something complicated as there are XML and do all the tasks that you can imagine simply without needed to code yourself all the parsing logic. I hope you are a happier developer since now when you need to manage an XML inside a shell script.

Etiquetas: