加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用lxml将XML转换为Python中的字典

发布时间:2020-12-16 23:22:07 所属栏目:百科 来源:网络整理
导读:StackOverflow上似乎有很多解决方案用于将 XML转换为 Python字典,但它们都没有生成我正在寻找的输出.我有以下XML: ?xml version="1.0" encoding="UTF-8"?status xmlns:mystatus="http://localhost/mystatus"section1 mystatus:field1="data1" mystatus:fiel
StackOverflow上似乎有很多解决方案用于将 XML转换为 Python字典,但它们都没有生成我正在寻找的输出.我有以下XML:

<?xml version="1.0" encoding="UTF-8"?>
<status xmlns:mystatus="http://localhost/mystatus">
<section1
    mystatus:field1="data1"
    mystatus:field2="data2" />
<section2
    mystatus:lineA="outputA"
    mystatus:lineB="outputB" />
</status>

lxml has an elegantly simple solution用于将XML转换为字典:

def recursive_dict(element):
 return element.tag,dict(map(recursive_dict,element)) or element.text

不幸的是,我得到:

('status',{'section2': None,'section1': None})

代替:

('status',{'section2': 
                       {'field1':'data1','field2':'data2'},'section1': 
                       {'lineA':'outputA','lineB':'outputB'}
            })

我无法弄清楚如何获得我想要的输出而不会使recursive_dict()函数大大复杂化.

我没有与lxml绑定,只要它给了我xml中的所有信息,我也可以使用不同的字典组织.谢谢!

解决方法

我个人喜欢 here的xmltodict.使用pip你可以像pip install xmltodict一样安装它.

请注意,这实际上创建了OrderedDict对象.用法示例:

import xmltodict as xd

with open('test.xml','r') as f:
    d = xd.parse(f)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读