I construct XML using The ElementTree XML API and I would like to be able to pretty-print
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
?
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:
lxml.etree.tostring
(answer #2): lxml.etree
is a near-perfect superset of the stdlib etree, so if you're going to use it for pretty-printing, just use it to build the XML in the first place.indent
/prettyprint
(answer #3): This expects an ElementTree
tree, which is exactly what you already have, not a string or file.