Pretty printing XML in Python Pretty printing XML in Python python python

Pretty printing XML in Python


import xml.dom.minidomdom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)pretty_xml_as_string = dom.toprettyxml()


lxml is recent, updated, and includes a pretty print function

import lxml.etree as etreex = etree.parse("filename")print etree.tostring(x, pretty_print=True)

Check out the lxml tutorial:http://lxml.de/tutorial.html


Another solution is to borrow this indent function, for use with the ElementTree library that's built in to Python since 2.5.Here's what that would look like:

from xml.etree import ElementTreedef indent(elem, level=0):    i = "\n" + level*"  "    j = "\n" + (level-1)*"  "    if len(elem):        if not elem.text or not elem.text.strip():            elem.text = i + "  "        if not elem.tail or not elem.tail.strip():            elem.tail = i        for subelem in elem:            indent(subelem, level+1)        if not elem.tail or not elem.tail.strip():            elem.tail = j    else:        if level and (not elem.tail or not elem.tail.strip()):            elem.tail = j    return elem        root = ElementTree.parse('/tmp/xmlfile').getroot()indent(root)ElementTree.dump(root)


matomo