Python pretty XML printer with lxml

prosseek picture prosseek · Feb 23, 2011 · Viewed 37.6k times · Source

After reading from an existing file with 'ugly' XML and doing some modifications, pretty printing doesn't work. I've tried etree.write(FILE_NAME, pretty_print=True).

I have the following XML:

<testsuites tests="14" failures="0" disabled="0" errors="0" time="0.306" name="AllTests">
    <testsuite name="AIR" tests="14" failures="0" disabled="0" errors="0" time="0.306">
....

And I use it like this:

tree = etree.parse('original.xml')
root = tree.getroot()

...    
# modifications
...

with open(FILE_NAME, "w") as f:
    tree.write(f, pretty_print=True)

Answer

woodm1979 picture woodm1979 · Mar 8, 2012

For me, this issue was not solved until I noticed this little tidbit here:

http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output

Short version:

Read in the file with this command:

>>> parser = etree.XMLParser(remove_blank_text=True)
>>> tree = etree.parse(filename, parser)

That will "reset" the already existing indentation, allowing the output to generate it's own indentation correctly. Then pretty_print as normal:

>>> tree.write(<output_file_name>, pretty_print=True)