Pretty print xml with python - indenting xml.
Here's a fairly simple way to pretty print xml with python. By pretty printing XML, I mean indenting XML with python nicely.
from xml.dom.ext import PrettyPrint
from xml.dom.ext.reader.Sax import FromXmlFile
import sys
doc = FromXmlFile(sys.argv[1])
PrettyPrint(doc, sys.stdout)
Are there any other ways to pretty print xml with python?
How do you pretty print xml with your favourite xml API? Pretty printing xml with ElementTree anyone?
UPDATE: there's a few other ways listed in the comments.
Written by a Melbourne web developer. Available for your projects - php, mysql, e commerce, javascript, CMS, css, flash, actionscript, python, games, postgresql, xml.
from xml.dom.ext import PrettyPrint
from xml.dom.ext.reader.Sax import FromXmlFile
import sys
doc = FromXmlFile(sys.argv[1])
PrettyPrint(doc, sys.stdout)
Are there any other ways to pretty print xml with python?
How do you pretty print xml with your favourite xml API? Pretty printing xml with ElementTree anyone?
UPDATE: there's a few other ways listed in the comments.
Written by a Melbourne web developer. Available for your projects - php, mysql, e commerce, javascript, CMS, css, flash, actionscript, python, games, postgresql, xml.
Comments
The last time I revisited this problem, I would up using a pretty-printing XSLT with lxml as the XSLT interface. It's faster than the fairly slow xml.dom.ext.PrettyPrint.
Mostly, though, I use a custom indent function for both lxml and cElementTree trees.
from xml.minidom import parseString
from xml.etree import ElementTree
def prettyPrint(element):
txt = ElementTree.tostring(element)
print minidom.parseString(txt).toprettyxml()
Excellent tips !! Thank you so much !