xq - XML Query Tool | Convert XML to Text

Use xq to query XML files and extract specific data. Convert XML to text format easily with this command-line utility.

xq - XML Query Tool

Introduction to xq

xq is a powerful command-line utility designed for querying XML files. It allows developers to easily extract specific data points from XML documents, transforming them into a more manageable text format. This tool is invaluable for automating data processing and integrating XML data into various workflows.

Download xq

Get the latest version of xq for your system:

wget -q -O - "https://github.com/sibprogrammer/xq/releases/download/v1.1.4/xq_1.1.4_linux_amd64.tar.gz" | tar zxv
install -o root -g root -m 0755 xq /usr/local/bin/xq

Usage Example: Extracting XML Data

To demonstrate the functionality of xq, let's prepare a sample XML file named test.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Name>fullnode-backup-2</Name>
  <Contents>
    <Key>archive-v1.tgz</Key>
    <LastModified>2023-04-20T15:13:12.000Z</LastModified>
    <Size>1493252335919</Size>
    <StorageClass>STANDARD</StorageClass>
  </Contents>
  <Contents>
    <Key>archive-v2.tgz</Key>
    <LastModified>2023-04-21T15:10:56.000Z</LastModified>
    <Size>1495321500561</Size>
    <StorageClass>STANDARD</StorageClass>
  </Contents>
</ListBucketResult>

Querying for Key Names

To retrieve all the key names from the XML file, you can use the following command:

cat test.xml | xq -x '/ListBucketResult/Contents/Key'

The output will be a plain text list of the key names:

archive-v1.tgz
archive-v2.tgz

Benefits of Using xq

xq simplifies complex XML parsing tasks, making it easier to work with structured data. Its command-line interface allows for seamless integration into scripts and automated processes. Whether you need to extract specific attributes, elements, or entire sections of an XML document, xq provides an efficient and straightforward solution.

Further Resources