formatted xml output from ElementTree inconsistency

Steven Bethard steven.bethard at gmail.com
Fri Jun 24 22:21:06 EDT 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)
[snip]
> 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<')
<root>
<parent>
<child />
</parent>
</root>

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

STeVe



More information about the Python-list mailing list