Preserve order of attributes when modifying with minidom
To keep the attribute order I made this slight modification in minidom:
from collections import OrderedDict
In the Element class :
__init__(...) self._attrs = OrderedDict() #self._attrs = {}writexml(...) #a_names.sort()
Now this will only work with Python 2.7+And I'm not sure if it actually works => Use at your own risks...
And please note that you should not rely on attribute order:
Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.
It is clear that xml attribute are not ordered.I just have found this strange behavior !
It seems that this related to a sort added in xml.dom.minidom.Element.writexml function !!
class Element(Node):... snip ... def writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() a_names = attrs.keys() a_names.sort()--------^^^^^^^^^^^^^^ for a_name in a_names: writer.write(" %s=\"" % a_name) _write_data(writer, attrs[a_name].value) writer.write("\"")
Removing the line restore a behavior which keep the order of the original document.It is a good idea when you have to check with diff tools that there is not a mistake in your code.