使用ElementTree将xml转换为字典 [英] Converting xml to dictionary using ElementTree

查看:195
本文介绍了使用ElementTree将xml转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ElementTree寻找一个XML到字典解析器,我已经找到了一些但是排除了这些属性,在我的例子中我有很多属性。

I'm looking for an XML to dictionary parser using ElementTree, I already found some but they are excluding the attributes, and in my case I have a lot of attributes.

推荐答案

def etree_to_dict(t):
    d = {t.tag : map(etree_to_dict, t.iterchildren())}
    d.update(('@' + k, v) for k, v in t.attrib.iteritems())
    d['text'] = t.text
    return d

致电

tree = etree.parse("some_file.xml")
etree_to_dict(tree.getroot())

只要你实际上没有一个属性 text ,这个工作就可以了如果这样做,则更改函数体中的第三行以使用其他键。此外,您无法处理与此混合的内容。

This works as long as you don't actually have an attribute text; if you do, then change the third line in the function body to use a different key. Also, you can't handle mixed content with this.

(在LXML上测试。)

(Tested on LXML.)

这篇关于使用ElementTree将xml转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆