For a computer, there's no need to order the elements - it's not necessary, and an unordered dictionary makes sense.
However, if you want them to be ordered for a user to read, this isn't a violation of the spec. It looks like you can do this by hacking (or forking) the standard ElementTree a small amount. The file is ElementTree.py
in xml.etree under lib.
First, the Element
object by default uses a standard, unordered dictionary for the attributes. Change it to use an ordered dictionary. That class definition is ~line 450 in my python 2.6 one. In py2.7+ this is in collections, in py2.6 you can find a backported implementation on the web.
Second, by default it sorts the keys when it writes (to help make sense of them). You need to turn this off. It's in ElementTree.write()
, and the line just says something like items.sort()
. Comment that out. This is line ~688 in the python 2.6 version.
Those two together allow you to create a tree and write the attributes in your own order.
If you want to read files in order too (I haven't actually tested this part), you also need to modify the parser:
looks like the functions are _start
and _start_list
(inside XMLTreeBuilder
) which both declare attrib = {}
, change that as well to be an ordered dictionary.