Preserve order of attributes when modifying with minidom

Is there a way I can preserve the original order of attributes when processing XML with minidom?

With minidom no, the datatype used to store attributes is an unordered dictionary. pxdom can do it, though it is considerably slower.


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.


Before Python 2.7, I used following hotpatching:

class _MinidomHooker(object):
    def __enter__(self):
        minidom.NamedNodeMap.keys_orig = minidom.NamedNodeMap.keys
        minidom.NamedNodeMap.keys = self._NamedNodeMap_keys_hook
        return self

    def __exit__(self, *args):
        minidom.NamedNodeMap.keys = minidom.NamedNodeMap.keys_orig
        del minidom.NamedNodeMap.keys_orig

    @staticmethod
    def _NamedNodeMap_keys_hook(node_map):
        class OrderPreservingList(list):
            def sort(self):
                pass
        return OrderPreservingList(node_map.keys_orig())

Used this way:

with _MinidomHooker():
    document.writexml(...)

Disclaimer:

  1. thou shall not rely on the order of attributes.
  2. mutating the NamedNodeMap class is not thread safe.
  3. hotpatching is evil.