Skip to content

Instantly share code, notes, and snippets.

@dieegorenan
Last active November 16, 2018 12:07
Show Gist options
  • Save dieegorenan/0385b2fe9ae08029cae355f92052a9db to your computer and use it in GitHub Desktop.
Save dieegorenan/0385b2fe9ae08029cae355f92052a9db to your computer and use it in GitHub Desktop.
Turn all XMLs of a directory into pretty.xml. Format the XMLs
"""
Format all XMLs from directory.
*.xml becomes *.pretty.xml
Usage:
xml_pretty_print.py <the_directory>
xml_pretty_print.py <the_file.xml>
"""
import xml.dom.minidom
import os
import sys
def pretty_xml(xml_file_input, xml_file_output):
if not os.path.isfile(xml_file_output):
print(f"printing {xml_file_input} into {xml_file_output}")
with open(xml_file_input, encoding="utf8") as xmldata:
my_xml = xml.dom.minidom.parseString(xmldata.read())
xml_pretty_str = my_xml.toprettyxml()
with open(xml_file_output, encoding="utf8", mode='w') as xmlout:
xmlout.write(xml_pretty_str)
else:
print(f"file already exists: {xml_file_output}")
if len(sys.argv) == 2:
if sys.argv[1].endswith(".xml"):
file_name = sys.argv[1]
pretty_xml(file_name, file_name.replace(".xml", ".pretty.xml"))
else:
root_dir = sys.argv[1]
for subdir, dirs, files in os.walk(root_dir):
for file in files:
file_path = os.path.join(subdir, file)
if file_path.endswith(".xml") and not file_path.endswith(".pretty.xml"):
pretty_xml(file_path, file_path.replace(".xml", ".pretty.xml"))
else:
print("invalid argument!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment