简体   繁体   中英

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 ?

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:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM