How to order xml element attributes in Python?

半世苍凉 提交于 2019-12-11 04:26:58

问题


When parsing an xml file into a Python ElementTree the attributes' order is mixed up because Python stores the attributes in a dictionary.

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


回答1:


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
>>>



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/5381296/how-to-order-xml-element-attributes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!