Search code examples
xmlunixcommand-line

How to pretty print XML from the command line?


Related: How can I pretty-print JSON in (unix) shell script?

Is there a (unix) shell script to format XML in human-readable form?

Basically, I want it to transform the following:

<root><foo a="b">lorem</foo><bar value="ipsum" /></root>

... into something like this:

<root>
    <foo a="b">lorem</foo>
    <bar value="ipsum" />
</root>

Solution

  • xmllint from libxml2

    xmllint --format file.xml
    

    (On Debian based distributions install the libxml2-utils package)

    xml_pp from the XML::Twig module

    xml_pp < file.xml
    

    (On Debian based distributions install the xml-twig-tools package)

    XMLStarlet

    xmlstarlet format --indent-tab file.xml
    

    Tidy

    tidy -xml -i -q file.xml
    

    Python's xml.dom.minidom

    echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
      python -c 'import sys, xml.dom.minidom; print(xml.dom.minidom.parseString(sys.stdin.read()).toprettyxml())'
    

    saxon-lint (my own project)

    saxon-lint --indent --xpath '/' file.xml
    

    saxon-HE

    echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
      java -cp /usr/share/java/saxon/saxon9he.jar net.sf.saxon.Query \
           -s:- -qs:/ '!indent=yes'
    

    xidel

    xidel --output-node-format=xml --output-node-indent -se . -s file.xml
    

    (Credit to Reino)

    Output for all commands:

    <root>
      <foo a="b">lorem</foo>
      <bar value="ipsum"/>
    </root>