Created
July 16, 2013 16:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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