Home > xml > Prettify (indent) XML files

Prettify (indent) XML files

Problem

You have an XML file but it’s not indented. Maybe the whole contents is in one line… How to transform it to a human readable form?

Solution

xmllint --format ugly.xml

Example:

Input:

<?xml version="1.0" encoding="UTF-8"?> <gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> <gesmes:subject>Reference rates</gesmes:subject> <gesmes:Sender> <gesmes:name>European Central Bank</gesmes:name> </gesmes:Sender> <Cube> <Cube time='2011-01-10'> <Cube currency='USD' rate='1.2903'/> <Cube currency='JPY' rate='107.17'/> </Cube> </Cube> </gesmes:Envelope>

Output:

<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
  <gesmes:subject>Reference rates</gesmes:subject>
  <gesmes:Sender>
    <gesmes:name>European Central Bank</gesmes:name>
  </gesmes:Sender>
  <Cube>
    <Cube time="2011-01-10">
      <Cube currency="USD" rate="1.2903"/>
      <Cube currency="JPY" rate="107.17"/>
    </Cube>
  </Cube>
</gesmes:Envelope>

Related Work

If you want to edit your XML files, you can try the oXygen XML editor. With oXygen you can do anything that you can imagine… If you register, you get a code and you can use the software for 30 days. Registration can be renewed.

Advertisements
  1. April 17, 2012 at 18:46

    Do you know how to save this output to the same file??
    For example if I do this:

    xmllint --format ugly.xml > somefile.xml

    The output of the contents it’s saved in that file, but if I do this:

    xmllint --format ugly.xml > ugly.xml

    I got:

    ugly.xml:1: parser error : Start tag expected, '<' not found

    Is there a way to overwrite the same file?? Thanks for this article thought ;)

    • April 17, 2012 at 22:02

      It’s not a good idea to redirect the output of xmllint to the input file. This way you can corrupt the input file, even lose its content. I suggest using a temp file:

      xmllint --format ugly.xml > temp; mv temp ugly.xml
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: