Search code examples
pythonxmlpython-2.7pretty-print

Python/XML: Pretty-printing ElementTree


I construct XML using The ElementTree XML API and I would like to be able to pretty-print

  • individual nodes (for inspection) as well as
  • the whole document (to a file, for future examination).

I can use use ET.write() to write my XML to file and then pretty-print it using many suggestions in Pretty printing XML in Python. However, this requires me to serialize and then deserialize the XML (to disk or to StringIO) just to serialize it again prettily - which is clearly suboptimal.

So, is there a way to pretty-print an xml.etree.ElementTree?


Solution

  • As the docs say, in the write method:

    file is a file name, or a file object opened for writing.

    This includes a StringIO object. So:

    outfile = cStringIO.StringIO()
    tree.write(of)
    

    Then you can just pretty-print outfile using your favorite method—just outfile.seek(0) then pass outfile itself to a function that takes a file, or pass outfile.getvalue() to a function that takes a string.


    However, notice that many of the ways to pretty-print XML in the question you linked don't even need this. For example: