671

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>
Community
  • 1
  • 1
svidgen
  • 13,744
  • 4
  • 33
  • 58
  • 1
    To have `xmllint` available on Debian systems, you need to install the package `libxml2-utils` (`libxml2` does not provide this tool, at least not on Debian 5.0 "Lenny" and 6.0 "Squeeze"). – twonkeys Sep 20 '13 at 13:03
  • 1
    web browsers (e.g. firefox / chrome) tend to do a good job of pretty-printing XML documents these days. (posting as a comment because this isn't a CLI, but a very convenient alternative) – Sam Mason Mar 29 '22 at 10:02

12 Answers12

1148

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'

xidel

You need xidel:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    xidel -s - -se . --output-node-format=xml --output-node-indent

(Credit to Reino)

Output for all commands:

<root>
  <foo a="b">lorem</foo>
  <bar value="ipsum"/>
</root>
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Good, quick answer. The first option seems like it'll be more ubiquitous on modern *nix installs. A minor point; but can it be called without working through an intermediate file? I.e., `echo '' | xmllint --some-read-from-stdn-option`? – svidgen Apr 18 '13 at 19:08
  • The package is `libxml2-utils` in my beautiful ubuntu. – franzlorenzon Feb 07 '14 at 09:23
  • Do you know how to wrap long lines? – DavidGamba May 01 '14 at 15:43
  • for the `xml_pp` option: you can install from the repositories `xml-twig-tools` (ubuntu) – Tobias Helbich Jun 24 '14 at 10:02
  • 2
    Note that the "cat data.xml | xmllint --format - | tee data.xml" does not work. On my system it sometimes worked for small files, but always truncated huge files. If you really want to do anything in place read http://backreference.org/2011/01/29/in-place-editing-of-files/ – user1346466 Dec 03 '14 at 18:55
  • I did this to use **xmllint**: `find . -name "*.xml" -exec xmllint --format --output {} {} \;` You have to can specify a file to it put the result of the pretty print. In my case, I just wanted to update the file, so the ouput file was the sameone as the input. – Pedro Witzel Aug 14 '15 at 07:26
  • 3
    To solve `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 805: ordinal not in range(128)` in python version you want to define `PYTHONIOENCODING="UTF-8"`: `cat some.xml | PYTHONIOENCODING="UTF-8" python -c 'import sys;import xml.dom.minidom;s=sys.stdin.read();print xml.dom.minidom.parseString(s).toprettyxml()' > pretty.xml` – FelikZ Nov 02 '16 at 11:16
  • `xmllint` seems to silently refuse to do any formatting if lines are too long. – Tgr Dec 08 '16 at 03:06
  • It seems tidy is only option to put attributes on separate lines. – George Sovetov Dec 15 '16 at 11:14
  • https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20#comment19202573_9942822 shows another fix for the unicode error in python when piping to a file. – Jasper Aug 07 '18 at 15:52
  • 4
    Note that **tidy** can also **format xml with no root element**. This is useful to format through a pipe, xml sections (e.g. extracted from logs). `echo '' | tidy -xml -iq` – Marinos An Oct 09 '19 at 11:49
  • Does any of these options work with `tail`? I'm able to `tail` a streaming log from a remote application which has XML fragments in it and would like the XML fragments to get formatted as the output stream rather than the formatting program hanging until `tail` is killed. I tried `tidy` and it only spits out format warnings as they are encountered. – Tim Lewis Nov 06 '19 at 12:52
  • 1
    didn't find any coloring options? any hints? for now I use vim to get coloring, but then I have to create a newly formatted xml to have good readability again – Markus Dec 09 '19 at 09:32
  • Which of these options are portable enough to run on Windows? – Aaron Franke Jun 17 '21 at 13:24
189

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

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

Orwellophile
  • 13,235
  • 3
  • 69
  • 45
crmpicco
  • 16,605
  • 26
  • 134
  • 210
  • 4
    sputnick's answer contains this information, but crmpicco's answer is the most useful answer here to the general question about how to pretty print XML. – Seth Difley Nov 26 '14 at 18:08
  • 4
    we can write out that formatted xml output to some other xml file and use that.. eg xmllint --format yourxmlfile.xml >> new-file.xml – LearnToLive Jan 13 '16 at 15:53
  • 2
    On Ubuntu 16.04 you can use the following: `sudo apt-get install libxml2-utils` – Melle Jan 24 '17 at 09:53
  • 1
    This works on Windows too; [`git`](https://git-scm.com) for Windows [download](https://git-scm.com/download/win) even installs a recent version of `xmllint`. Example: `"C:\Program Files\Git\usr\bin\xmllint.exe" --format QCScaper.test@borland.com.cds.xml > QCScaper.test@borland.com.pretty-printed.cds.xml` – Jeroen Wiert Pluimers Dec 21 '17 at 07:46
  • From MacOS with libxml2 installed via brew. To unminify an xml and save it to a new file for me it worked this command `xmllint --format in.xml > out.xml` – Ax_ Jul 05 '21 at 20:34
45

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).

matanster
  • 15,072
  • 19
  • 88
  • 167
  • 1
    Helpful, because I couldn't get xmllint to add linebreaks to a single line xml file. Thanks! – xlttj Nov 12 '14 at 16:00
  • `tidy` works well for me too. Unlike `hxnormalize`, this done actually closes the `` tag. – Sridhar Sarnobat Nov 25 '14 at 23:07
  • 12
    BTW, here are some options that I have found useful: `tidy --indent yes --indent-spaces 4 --indent-attributes yes --wrap-attributes yes --input-xml yes --output-xml yes < InFile.xml > OutFile.xml`. – Victor Yarema Feb 19 '16 at 10:02
  • 3
    Great tip @VictorYarema. I combined it with pygmentize and added it to my .bashrc: `alias prettyxml='tidy --indent yes --indent-spaces 4 --indent-attributes yes --wrap-attributes yes --input-xml yes --output-xml yes | pygmentize -l xml'` and then can `curl url | prettyxml` – Net Wolf Nov 12 '17 at 23:45
21

Without installing anything on macOS / most Unix.

Use tidy

cat filename.xml | tidy -xml -iq

Redirecting viewing a file with cat to tidy specifying the file type of xml and to indent while quiet output will suppress error output. JSON also works with -json.

jasonleonhard
  • 12,047
  • 89
  • 66
  • 2
    You don't need the `cat` step: `tidy -xml -iq filename.xml`. Also, you can even do `tidy -xml -iq filename.xml` using the `-m` option to *modify* the original file... – janniks Mar 03 '20 at 08:36
14

You didn't mention a file, so I assume you want to provide the XML string as standard input on the command line. In that case, do the following:

$ echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' | xmllint --format -
David
  • 6,462
  • 2
  • 25
  • 22
14

xmllint support formatting in-place:

for f in *.xml; do xmllint -o $f --format $f; done

As Daniel Veillard has written:

I think xmllint -o tst.xml --format tst.xml should be safe as the parser will fully load the input into a tree before opening the output to serialize it.

Indent level is controlled by XMLLINT_INDENT environment variable which is by default 2 spaces. Example how to change indent to 4 spaces:

XMLLINT_INDENT='    '  xmllint -o out.xml --format in.xml

You may have lack with --recover option when you XML documents are broken. Or try weak HTML parser with strict XML output:

xmllint --html --xmlout <in.xml >out.xml

--nsclean, --nonet, --nocdata, --noblanks etc may be useful. Read man page.

apt-get install libxml2-utils
dnf install libxml2
apt-cyg install libxml2
brew install libxml2
gavenkoa
  • 45,285
  • 19
  • 251
  • 303
4

This simple(st) solution doesn't provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.

Use sed to replace '<' with itself preceeded with a newline.

And as mentioned by Gilles, it's probably not a good idea to use this in production.

# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l

# check the output looks generally ok
sed 's/</\n</g' sample.xml | head

# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml
nby
  • 119
  • 1
  • 3
3

This took me forever to find something that works on my mac. Here's what worked for me:

brew install xmlformat
cat unformatted.html | xmlformat
Sridhar Sarnobat
  • 25,183
  • 12
  • 93
  • 106
1

With :

$ xidel -s input.xml -e . --output-node-format=xml --output-node-indent
$ xidel -s input.xml -e 'serialize(.,{"indent":true()})'

$ echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' | \
  xidel -se . --output-node-format=xml --output-node-indent
$ echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' | \
  xidel -se 'serialize(.,{"indent":true()})'
Reino
  • 3,203
  • 1
  • 13
  • 21
  • The first solution appears to be out of date as neither option is in `xidel --help` and although the second solution throws no error (the echoed solution needs `-` after `xidel` to receive standard input) this also does not indent the xml. – potong Aug 11 '23 at 09:12
  • @potong Please use an [up-to-date binary](https://videlibri.sourceforge.net/xidel.html#downloads). – Reino Aug 12 '23 at 11:50
  • This was based on the last official release Xidel 0.9.8. – potong Aug 13 '23 at 07:04
1

yq can be used to pretty print XML. It has an option to define the indent.

yq --input-format xml --output-format xml --indent 2
jpseng
  • 1,618
  • 6
  • 18
  • there is also yq -P but I tried it and looks like not really working. Just `yq --input-format xml --output-format xml` produced a well formatted XML – Sergey Ponomarev Mar 18 '23 at 16:39
0

Edit:

Disclaimer: you should usually prefer installing a mature tool like xmllint to do a job like this. XML/HTML can be a horribly mutilated mess. However, there are valid situations where using existing tooling is preferable over manually installing new ones, and where it is also a safe bet the XML's source is valid (enough). I've written this script for one of those cases, but they are rare, so precede with caution.


I'd like to add a pure Bash solution, as it is not 'that' difficult to just do it by hand, and sometimes you won't want to install an extra tool to do the job.

#!/bin/bash

declare -i currentIndent=0
declare -i nextIncrement=0
while read -r line ; do
  currentIndent+=$nextIncrement
  nextIncrement=0
  if [[ "$line" == "</"* ]]; then # line contains a closer, just decrease the indent
    currentIndent+=-1
  else
    dirtyStartTag="${line%%>*}"
    dirtyTagName="${dirtyStartTag%% *}"
    tagName="${dirtyTagName//</}"
    # increase indent unless line contains closing tag or closes itself
    if [[ ! "$line" =~ "</$tagName>" && ! "$line" == *"/>"  ]]; then
      nextIncrement+=1
    fi
  fi

  # print with indent
  printf "%*s%s" $(( $currentIndent * 2 )) # print spaces for the indent count
  echo $line
done <<< "$(cat - | sed 's/></>\n</g')" # separate >< with a newline

Paste it in a script file, and pipe in the xml. This assumes the xml is all on one line, and there are no extra spaces anywhere. One could easily add some extra \s* to the regexes to fix that.

Leon S.
  • 3,337
  • 1
  • 19
  • 16
0

I would:

nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ cat ugly.xml 


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

nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> create database pretty
Database 'pretty' created in 231.32 ms.
> 
> open pretty
Database 'pretty' was opened in 0.05 ms.
> 
> set parser xml
PARSER: xml
> 
> add ugly.xml
Resource(s) added in 161.88 ms.
> 
> xquery .
<root>
  <foo a="b">lorem</foo>
  <bar value="ipsum"/>
</root>
Query executed in 179.04 ms.
> 
> exit
Have fun.
nicholas@mordor:~/flwor$ 

if only because then it's "in" a database, and not "just" a file. Easier to work with, to my mind.

Subscribing to the belief that others have worked this problem out already. If you prefer, no doubt eXist might even be "better" at formatting xml, or as good.

You can always query the data various different ways, of course. I kept it as simple as possible. You can just use a GUI, too, but you specified console.