Skip to content

Instantly share code, notes, and snippets.

@guyc
Created March 21, 2016 01:25
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 guyc/5f0d1098bc960d0ecd08 to your computer and use it in GitHub Desktop.
Save guyc/5f0d1098bc960d0ecd08 to your computer and use it in GitHub Desktop.
This is a quick-and-dirty tool to reformat XML configuration files to make it possible to diff them. It only preserves tag and attribute values.
#!/usr/bin/python
from xml.etree import ElementTree as ET
import sys
def compareString(a,b):
aLower = a.lower()
bLower = b.lower()
order = 0
if aLower > bLower:
order = 1
elif aLower < bLower:
order = -1
return order
def compareAttr(attr, a, b):
order = 0
if attr in a.attrib and attr in b.attrib:
#print ("comparing",a.attrib[attr],b.attrib[attr])
order = compareString(a.attrib[attr], b.attrib[attr])
return order
def compareNodes(a,b):
order = compareString(a.tag, b.tag)
if order == 0:
order = compareAttr("key", a, b)
return order
def sortedChildren(root):
children = []
for child in root:
children.append(child)
return sorted(children, cmp=compareNodes)
def printSorted(node, indent=0):
sys.stdout.write(' ' * indent)
sys.stdout.write('<'+node.tag)
if len(node.attrib) > 2:
for key,value in sorted(node.attrib.iteritems()):
sys.stdout.write("\n")
sys.stdout.write(' ' * (1+indent))
sys.stdout.write(key+'="'+value+'"')
sys.stdout.write("\n")
sys.stdout.write(' ' * indent)
else:
for key,value in node.attrib.iteritems():
sys.stdout.write(' '+key+'="'+value+'"')
if len(node) > 0:
sys.stdout.write('>')
sys.stdout.write("\n")
for child in sortedChildren(node):
printSorted(child, indent+1)
sys.stdout.write(' ' * indent)
sys.stdout.write('</'+node.tag+'>')
else:
sys.stdout.write(' />')
sys.stdout.write("\n")
if len(sys.argv) != 2:
exit -1
else:
fileName = sys.argv[1]
xml = ET.parse(fileName)
root = xml.getroot()
printSorted(root, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment