我有下列函数,它可以把一个XML文件粗略地解析成一个字典。不幸的是,由于Python字典是无序的,我不能按照想要的顺序循环遍历节点。
如何更改这个函数以输出一个有序的字典,可以在使用for循环遍历时反映出原始节点的顺序?
如何更改这个函数以输出一个有序的字典,可以在使用for循环遍历时反映出原始节点的顺序?
def simplexml_load_file(file):
import collections
from lxml import etree
tree = etree.parse(file)
root = tree.getroot()
def xml_to_item(el):
item = None
if el.text:
item = el.text
child_dicts = collections.defaultdict(list)
for child in el.getchildren():
child_dicts[child.tag].append(xml_to_item(child))
return dict(child_dicts) or item
def xml_to_dict(el):
return {el.tag: xml_to_item(el)}
return xml_to_dict(root)
x = simplexml_load_file('routines/test.xml')
print x
for y in x['root']:
print y
输出:
{'root': {
'a': ['1'],
'aa': [{'b': [{'c': ['2']}, '2']}],
'aaaa': [{'bb': ['4']}],
'aaa': ['3'],
'aaaaa': ['5']
}}
a
aa
aaaa
aaa
aaaaa
如何实现collections.OrderedDict
,以便我可以确保获取节点的正确顺序?
参考 XML 文件:
<root>
<a>1</a>
<aa>
<b>
<c>2</c>
</b>
<b>2</b>
</aa>
<aaa>3</aaa>
<aaaa>
<bb>4</bb>
</aaaa>
<aaaaa>5</aaaaa>
</root>
six
库进行2.x / 3.x兼容性)b)在3.7中几乎不需要此功能,因为语言现在保证字典保证插入顺序,除非您想要任意或变化的顺序。 - smci