Created
July 26, 2012 12:43
-
-
Save codeinthehole/3181820 to your computer and use it in GitHub Desktop.
Format 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
#!/usr/bin/env python | |
import sys | |
import re | |
from xml.dom.minidom import parseString | |
def format_xml(xml_str): | |
xml_str = re.sub(r'\s*\n\s*', '', xml_str) | |
ugly = parseString(xml_str).toprettyxml(indent=' ') | |
regex = re.compile(r'>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL) | |
return regex.sub('>\g<1></', ugly) | |
if __name__ == '__main__': | |
if len(sys.argv) == 2: | |
f = open(file, 'r') | |
else: | |
f = sys.stdin | |
print format_xml(f.read()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use to re-format XML, passing a file or reading from STDIN::