相关疑难解决方法(0)

如何重写此函数以实现OrderedDict?

我有以下函数,它将XML文件解析为字典.

不幸的是,由于Python字典没有排序,我无法按照我的意愿循环遍历节点.

如何更改此值以便输出一个有序字典,该字典反映了使用'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
Run Code Online (Sandbox Code Playgroud)

输出:

{'root': {
    'a': ['1'],
    'aa': [{'b': [{'c': ['2']}, '2']}],
    'aaaa': [{'bb': ['4']}],
    'aaa': ['3'],
    'aaaaa': ['5']
}}

a
aa
aaaa
aaa
aaaaa …
Run Code Online (Sandbox Code Playgroud)

python xml collections lxml

13
推荐指数
1
解决办法
7186
查看次数

标签 统计

collections ×1

lxml ×1

python ×1

xml ×1