Use xml.etree.ElementTree to print nicely formatted xml files

PythonXmlElementtree

Python Problem Overview


I am trying to use xml.etree.ElementTree to write out xml files with Python. The issue is that they keep getting generated in a single line. I want to be able to easily reference them so if it's possible I would really like to be able to have the file written out cleanly.

This is what I am getting:

<Language><En><Port>Port</Port><UserName>UserName</UserName></En><Ch><Port>IP地址</Port><UserName>用户名称</UserName></Ch></Language>

This is what I would like to see:

<Language>
    <En>
        <Port>Port</Port>
        <UserName>UserName</UserName>
    </En>
    <Ch>
        <Port>IP地址</Port>
        <UserName>用户名称</UserName>
    </Ch>
</Language>

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheBeardedBerryView Question on Stackoverflow
Solution 1 - PythonMaxime ChéramyView Answer on Stackoverflow
Solution 2 - PythonmmmmmmView Answer on Stackoverflow