Skip to content

Instantly share code, notes, and snippets.

@ericjsilva
Created July 16, 2013 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericjsilva/6010490 to your computer and use it in GitHub Desktop.
Save ericjsilva/6010490 to your computer and use it in GitHub Desktop.
Uses the lxml and etree packages to pretty print an XML file passed in as an argument. For example: % python prettyprintxml.py myxmlfile.xml
from lxml import etree
import sys
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
for e in elem:
indent(e, level+1)
if not e.tail or not e.tail.strip():
e.tail = i + " "
if not e.tail or not e.tail.strip():
e.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if len(sys.argv) > 1:
src = sys.argv[1]
else:
src = sys.stdin
tree = etree.parse(src)
indent(tree.getroot())
tree.write("prettyprint.xml", "utf-8")
print "Finished formatting %s to prettyprint.xml." % src
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment