开发者

How to order xml element attributes in Python?

When parsing an xml file into a Python ElementTree the attributes' order is mixe开发者_如何学Pythond up because Python stores the attributes in a dictionary.

How can I change the order of the attributes in the dictionary?


XML attributes are by definition unordered1, compare paragraph 3.1 of the official standard.

1Technically, attribute lists are ordered, but the order is not significant, i.e. writers, transformers and parsers are free to switch it around as they like.


Your self-answer is as you said long and cumbersome. It doesn't need to be. Also it will fail if (1) there are more than 10 keys (2) a dict has fewer keys than than expected.

Try this; it's much simpler:

>>> ordered_keys = ('z', 'y', 'e', 'x', 'w') # possible keys, in desired order

Note: the above line is all the setup that is required.

>>> dic = {'z':'a', 'y':'b', 'x':'c', 'w':'d'} # actual contents of a dictionary
>>> for k in ordered_keys:
...     if k in dic: # avoid trouble if a key is missing
...         print k, dic[k]
...
z a
y b
x c
w d
>>>


XML does not define any ordering of attributes of a node. So the behavior is fine. If you make assumptions about the ordering of attributes then your assumptions are wrong. There is no ordering and you must not expect any kind of attribute ordering. So your question is invalid.


You can not change the order of attributes internally in the dictionary. This is impossible unless you do some fancy hacking.

The solution therefore, is to manually access the attributes in the order you want them, or create a list of the keys/items and sort that the way you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜