I simply solved it with the indent() function:
xml.etree.ElementTree.indent(tree, space=" ", level=0)Appends whitespace to the subtree to indent the tree visually. This can be used to generate pretty-printed XML output. tree can be anElementorElementTree.spaceis the whitespace string that will be inserted for each indentation level, two space characters by default. For indenting partial subtrees inside of an already indented tree, pass the initial indentation level aslevel.
tree = ET.ElementTree(root)
ET.indent(tree, space="\t", level=0)
tree.write(file_name, encoding="utf-8")
Note, the indent() function was added in Python 3.9.
I simply solved it with the indent() function:
xml.etree.ElementTree.indent(tree, space=" ", level=0)Appends whitespace to the subtree to indent the tree visually. This can be used to generate pretty-printed XML output. tree can be anElementorElementTree.spaceis the whitespace string that will be inserted for each indentation level, two space characters by default. For indenting partial subtrees inside of an already indented tree, pass the initial indentation level aslevel.
tree = ET.ElementTree(root)
ET.indent(tree, space="\t", level=0)
tree.write(file_name, encoding="utf-8")
Note, the indent() function was added in Python 3.9.
Whatever your XML string is, you can write it to the file of your choice by opening a file for writing and writing the string to the file.
from xml.dom import minidom
xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")
with open("New_Database.xml", "w") as f:
f.write(xmlstr)
There is one possible complication, especially in Python 2, which is both less strict and less sophisticated about Unicode characters in strings. If your toprettyxml method hands back a Unicode string (u"something"), then you may want to cast it to a suitable file encoding, such as UTF-8. E.g. replace the one write line with:
f.write(xmlstr.encode('utf-8'))
import xml.dom.minidom
dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
lxml is recent, updated, and includes a pretty print function
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)
Check out the lxml tutorial: https://lxml.de/tutorial.html
You can use the function toprettyxml() from xml.dom.minidom in order to do that:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.
Source: http://pymotw.com/2/xml/etree/ElementTree/create.html
You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
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.etreeis 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.- Effbot
indent/prettyprint(answer #3): This expects anElementTreetree, which is exactly what you already have, not a string or file.