← Full reference

xmllint

Checking, formatting, schema validation and XPath queries for XML — --format, --xpath, string(), count()

xmllint from libxml2 checks that XML is well-formed, validates it against a DTD or XSD schema, pretty-prints it and extracts data with XPath queries. For XML it's what jq is for JSON.

Syntax

xmllint [options] file.xml…

Instead of a file name you can give -, and the XML is read from stdin. Without options xmllint parses the document and prints it back — this way parse errors are visible.

Checking and validation

OptionWhat it does
--nooutdon't print the document — only report errors
--validvalidate against the DTD declared in the document itself (<!DOCTYPE …>)
--dtdvalid file.dtdvalidate against an external DTD
--schema file.xsdvalidate against an XML Schema (XSD)
--relaxng file.rngvalidate against a RELAX NG schema
--recoveron parse errors, output whatever could be parsed
--htmlparse as HTML (forgives unclosed tags)
--nonetdon't fetch DTDs and entities from the network
--hugelift internal limits on document size

Output and transformation

OptionWhat it does
--formatoutput with indentation; the indent width is set by the XMLLINT_INDENT variable (two spaces by default)
--noblanksremove insignificant spaces and newlines — XML on one line
--output file (-o)write the result to a file instead of stdout
--encode ENCODINGoutput in another encoding
--c14ncanonical form: attributes, quotes and empty tags in a uniform style; together with --noblanks it's handy for comparing documents with diff
--dropdtdremove <!DOCTYPE …>
--noentsubstitute entity values
--xincludeprocess <xi:include>
--nscleanremove redundant namespace declarations

Queries

OptionWhat it does
--xpath 'expression'evaluate XPath and print the result (the document itself isn't printed)
--shellinteractive shell: cat //title, ls, cd, exit

XPath: paths

ExpressionWhat it selects
/catalog/bookbook elements directly inside the root catalog
//titleall titles at any depth
*, @*any element / any attribute
//book/@idid attributes
//title/text()the text inside elements, without tags
..parent: //title[../@id="3"]
//book[@lang="de"]filter by attribute
//book[price > 8]filter by a child element's value
//book[1], //book[last()], [position() < 3]by position within its parent (from 1), the last, the first two
(//title)[2]the second title in the whole document
a | bunion of two node sets
parent::, ancestor::, following-sibling::, preceding-sibling::axes: parent, ancestors, siblings after / before

XPath: functions and operators

FunctionWhat it does
string(…)the text value of the first node found
count(…), sum(…)number of nodes, sum of values
contains(a, b), starts-with(a, b)substring, prefix
normalize-space(…)trim spaces at the edges and collapse inner ones
concat(a, b, …), string-length(…), translate(s, abc, ABC)concatenation, length, character-by-character replacement
name(…), local-name(…)element name with / without the namespace prefix
not(…), boolean(…)negation, "was anything found"
and, or, =, !=, <, >logic and comparisons in […] conditions

Exit codes

0 — all fine, 1 — parse error (the XML is broken) or file not found, 3 / 4 — the document failed schema / DTD validation, 10 — XPath found nothing or the expression has an error.

Examples

cat > books.xml <<'EOF'
<catalog><book id="1" lang="en"><title>Dune</title><price>9.99</price></book><book id="2" lang="de"><title>Solaris</title><price>7.50</price></book></catalog>
EOF

# check the syntax: silent if all is well
xmllint --noout books.xml && echo OK

# pretty-print
xmllint --format books.xml

# whole elements, with tags
xmllint --xpath '//title' books.xml

# text only — one line per node
xmllint --xpath '//title/text()' books.xml

# a single value: the title of the book with id=2
xmllint --xpath 'string(//book[@id="2"]/title)' books.xml

# an attribute value without the id="…" wrapper
xmllint --xpath 'string(//book[1]/@lang)' books.xml

# how many books and the sum of the prices
xmllint --xpath 'count(//book)' books.xml
xmllint --xpath 'sum(//price)' books.xml

# search by part of the text
xmllint --xpath '//book[contains(title, "un")]/@id' books.xml

# validate the document against an XSD schema
xmllint --noout --schema catalog.xsd books.xml

# XML from stdin
echo '<a><b>1</b></a>' | xmllint --format -

# compare two documents ignoring formatting
diff <(xmllint --noblanks --c14n a.xml) <(xmllint --noblanks --c14n b.xml)

Pitfalls

  • string() takes only the first node. string(//title) returns Dune, not all the titles. For all values use //title/text(), for the N-th — string((//title)[N]).
  • //book[2] isn't "the second book in the document", but every book that is the second child of its parent. For document-wide numbering you need parentheses: (//book)[2].
  • //book/@id prints id="1" together with the attribute name. To get just the value, use string(…/@id).
  • An empty result is an error. If XPath found nothing, xmllint prints XPath set is empty and exits with code 10. But string() of an empty set is just an empty string and code 0.
  • Namespaces. If the root has xmlns="…", the query //v finds nothing, and //p:v gives Undefined namespace prefix. The workaround: //*[local-name()="v"].
  • Whitespace in text is preserved. <title> Dune </title> returns the value with spaces — an = comparison won't match. Use normalize-space().
  • Quotes. Put the expression in single quotes, and strings inside the XPath in double quotes: '//book[@lang="de"]'.
  • In old libxml2 versions, text() results are glued together without a newline. If the values run together, iterate over the nodes by index.

See also

jq · yq · grep · sed · iconv