The xmlstarlet
command is a versatile command-line utility for parsing, transforming, and querying XML documents. It allows users to manipulate XML data easily, making it a valuable tool for developers and system administrators working with XML files.
The basic syntax of the xmlstarlet
command is as follows:
xmlstarlet [options] [arguments]
xmlstarlet sel
: Selects nodes from an XML document.xmlstarlet ed
: Edits an XML document.xmlstarlet tr
: Transforms an XML document using XSLT.xmlstarlet val
: Validates an XML document against a schema.xmlstarlet fo
: Formats an XML document for readability.To select specific nodes from an XML file, you can use the sel
option. For example, to select all book
elements from a books.xml
file:
xmlstarlet sel -t -m "//book" -v "title" -n books.xml
To add a new element to an existing XML document, use the ed
option. For instance, to add a new author
to a book
:
xmlstarlet ed -s "//book" -t elem -n "author" -v "New Author" books.xml
To transform an XML document using an XSLT stylesheet, use the tr
option. Here’s an example:
xmlstarlet tr stylesheet.xsl input.xml > output.xml
To validate an XML file against a schema, use the val
option. For example:
xmlstarlet val -e schema.xsd input.xml
To format an XML file for better readability, use the fo
option:
xmlstarlet fo input.xml
-n
option with sel
to suppress the output of the selected nodes if you only need to check the existence of nodes.