I have this simple py script that makes an xml file and saves, it and was wondering if there was a simple way to indent it?
import xml.etree.cElementTree as ET
root = ET.Element("root")
doc = ET.SubElement(root, "doc", location="one")
ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"
I looked at some other SO Q&A's Pretty printing XML in Python but these seem to mostly require other external libs? and was wondering if there is a way to not use those?
Thanks for the help.
You could use the standard library's minidom module's
toprettyxml
method:yields
Or, if you prefer the
ElementTree
methods for creating XML and don't mind being a bit inefficient, you could useElementTree
to write the unformatted XML to a StringIO (for Python2) or ByteIO (for Python3), parse that into a minidom Document, and then write it back out again usingtoprettyxml
: