[d]python解析xml后,节点的属性顺序发生了变化
本帖最后由 fibbery 于 2012-07-11 15:05:14 编辑 比如说一个xml文件的节点如下:
<Queue Name="CHS_DHC_KLB" ID="23561" />
<Queue Name="CHS_DHC_EHB" ID="23562" />
<Queue Name="CHS_DHC_DVB" ID="23563" />
<Queue ID="23561" Name="CHS_DHC_KLB" />
<Queue ID="23562" Name="CHS_DHC_EHB" />
<Queue ID="23563" Name="CHS_DHC_DVB" />
>>> d = {'Name':'test','ID':'2232'}
>>> d
{'Name': 'test', 'ID': '2232'}
>>> for k,v in d.items():
print k,v
Name test
ID 2232
>>>
from xml.dom.minidom import parseString, getDOMImplementation
from collections import OrderedDict
impl = getDOMImplementation()
dom3 = parseString('''<hello><Queue Name="CHS_DHC_KLB" ID="23561" /><Queue Name="CHS_DHC_EHB" ID="23562" /><Queue Name="CHS_DHC_DVB" ID="23563" /></hello>''')
newdom = impl.createDocument(None, 'out', None)
queues=dom3.getElementsByTagName("Queue")
root=newdom.documentElement
for queue in queues:
item=newdom.createElement("Queue")
item.setAttribute("Name",queue.getAttribute("Name"))
item.setAttribute("ID",queue.getAttribute("ID"))
# item._attrs=OrderedDict([('one','hello'), ('tow','world'), ('three', 'good')])
root.appendChild(item)
print newdom.toxml()
,试试看?
$ python
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict as dict
>>> d = {'Name':'test','ID':'2232','AAA':'aaa','BBB':'bbb'}
>>> dd = dict(Name='test',ID='2232',AAA='aaa',BBB='bbb')
>>> for k,v in d.items():
... print k,v
...
AAA aaa
Name test
BBB bbb
ID 2232
>>> for k,v in dd.items():
... print k,v
...
AAA aaa
ID 2232
BBB bbb
Name test
>>>