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
?
I was having issues using pretty print. Digging more into it I found the below solution which worked for me.
import xml.etree.cElementTree as etree
from xml.dom import minidom
root = etree.Element("root")
animal = etree.SubElement(root, "animal")
etree.SubElement(animal, "pet").text = "dog"
xmlstr =
minidom.parseString(etree.toString(root)).toprettyxml(indent = " ")
print (xmlstr)
Returns the result in XML format
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.