How to pretty print XML from the command line? How to pretty print XML from the command line? xml xml

How to pretty print XML from the command line?


xmllint

This utility comes with libxml2-utils:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |    xmllint --format -

Perl's XML::Twig

This command comes with XML::Twig module, sometimes xml-twig-tools package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |    xml_pp

xmlstarlet

This command comes with xmlstarlet:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |    xmlstarlet format --indent-tab

tidy

Check the tidy package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |    tidy -xml -i -

Python

Python's xml.dom.minidom can format XML (works also on legacy python2):

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

saxon-lint

You need saxon-lint:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |    saxon-lint --indent --xpath '/' -

saxon-HE

You need 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'


xmllint --format yourxmlfile.xml

xmllint is a command line XML tool and is included in libxml2 (http://xmlsoft.org/).

================================================

Note: If you don't have libxml2 installed you can install it by doing the following:

CentOS

cd /tmpwget ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gztar xzf libxml2-2.8.0.tar.gzcd libxml2-2.8.0/./configuremakesudo make installcd

Ubuntu

sudo apt-get install libxml2-utils

Cygwin

apt-cyg install libxml2

MacOS

To install this on MacOS with Homebrew just do:brew install libxml2

Git

Also available on Git if you want the code:git clone git://git.gnome.org/libxml2


You can also use tidy, which may need to be installed first (e.g. on Ubuntu: sudo apt-get install tidy).

For this, you would issue something like following:

tidy -xml -i your-file.xml > output.xml

Note: has many additional readability flags, but word-wrap behavior is a bit annoying to untangle (http://tidy.sourceforge.net/docs/quickref.html).