formatted xml output from ElementTree inconsistency

Steven Bethard steven.bethard at
Sat Jun 25 04:21:06 CEST 2005

Matthew Thorley wrote:
> from elementtree import ElementTree as et
> xmla = et.ElementTree('some_file.xml')
> xmlb = et.Element('parent')
> et.SubElement(xmlb, 'child1')
> et.SubElement(xmlb, 'child2')
> root = et.Element('root')
> root.append(xmla.getroot())
> root.append(xmlb)
> print et.tostring(root)
> Is their a function to 'pretty print' an element?

Depends on how pretty you want it.  I've found that putting each element 
on its own line has been sufficient for many of my manual-inspection use 
cases.  This isn't too hard with a cheap hack:

py> import elementtree.ElementTree as et
py> root = et.Element('root')
py> parent = et.SubElement(root, 'parent')
py> child = et.SubElement(parent, 'child')
py> print et.tostring(root)
<root><parent><child /></parent></root>
py> print et.tostring(root).replace('><', '>\n<')
<child />

Not ideal, but it may work well enough for you.


More information about the Python-list mailing list