Skip to content

Instantly share code, notes, and snippets.

@lucasrowe
Created May 2, 2012 04:56
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 lucasrowe/2573841 to your computer and use it in GitHub Desktop.
Save lucasrowe/2573841 to your computer and use it in GitHub Desktop.
Python Script for Pretty Printing XML - Allows for Piping
import re
import sys
import xml.dom.minidom
def printPretty(xml):
uglyXml = xml.toprettyxml()
# Clean it up
# from http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python
text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
prettyXml = text_re.sub('>\g<1></', uglyXml)
print prettyXml
if len(sys.argv) == 2:
text = sys.argv[1]
xml = xml.dom.minidom.parse(text)
printPretty(xml)
if __name__ == "__main__":
if len(sys.argv) == 1:
text = sys.stdin
xml = xml.dom.minidom.parse(text)
printPretty(xml)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment