How To Pretty-Print a Python ElementTree Structure
ElementTree doesn’t support pretty-printing XML. lxml does, but isn’t installed on our system. minidom‘s toprettyxml() is seriously fucked up. What to do? Turned out PyXML was installed, so I took some advice from here and came up with this function, which takes an ET node and returns a pretty-printed string:
import xml.etree.ElementTree as ET from xml.dom.ext.reader import Sax2 from xml.dom.ext import PrettyPrint from StringIO import StringIO def prettyPrintET(etNode): reader = Sax2.Reader() docNode = reader.fromString(ET.tostring(etNode)) tmpStream = StringIO() PrettyPrint(docNode, stream=tmpStream) return tmpStream.getvalue()
rajbot 5:37 pm on July 29, 2009 Permalink | Log in to Reply
xml.dom.ext seems completely undocumented on the web.
http://docs.python.org/library/xml.dom.ext gives a 404
Here is what pydoc xml.dom.ext says about PrettyPrint():
Dan 9:31 am on July 30, 2009 Permalink | Log in to Reply
This is where I like the lxml module for all my Python XML handling.
Of coure, if you just have an XML file the xmllint binary on unix systems is even better.
Dan
Anand Chitipothu 9:45 pm on January 1, 2010 Permalink | Log in to Reply
Looks like xml.dom.ext is not part of Python Standard Library. It is added by installing PyXML.
source: http://www.xml.com/pub/a/2002/09/25/py.html
Found a prettyprint utility in “Element Library Functions”.
http://effbot.org/zone/element-lib.htm#prettyprint