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>

Try doing this :

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

This utility comes with libxml2-utils

or

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

this command comes with XML::Twig perl module, sometimes xml-twig-tools package.

or

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

this command comes with xmlstarlet

or

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

check tidy package

or

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()'

or

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

check saxon-lint

or

 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'

Check saxon-HE


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 /tmp
wget ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gz
tar xzf libxml2-2.8.0.tar.gz
cd libxml2-2.8.0/
./configure
make
sudo make install
cd

Ubuntu

sudo apt-get install libxml2-utils

MacOS

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


You can also use tidy, which may need to be installed first (eg 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).

链接地址: http://www.djcxy.com/p/1288.html

上一篇: 任何人都可以用通俗的话来解释JSONP是什么?

下一篇: 如何从命令行漂亮地打印XML?