使用lxm在Python中将XML转换为字典

2024-05-29 06:03:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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'}
            })

如果不使递归的dict()函数复杂化,我就无法找到获得所需输出的方法。

我没有绑定到lxml,我也可以使用不同的字典组织,只要它提供xml中的所有信息。谢谢!


Tags: 字典statusxmlelementdictfield2field1data1
1条回答
网友
1楼 · 发布于 2024-05-29 06:03:13

我个人喜欢here中的xmltodict。有了pip,您可以像这样pip install xmltodict安装它。

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

import xmltodict as xd

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

相关问题 更多 >

    热门问题