python - 在python中将XML转换为字典列表
问题描述
我对python很陌生,请同样对待我。当我尝试将 XML 内容转换为字典列表时,我得到了输出,但没有达到预期的效果,并且尝试了很多。
XML 内容:
<project>
<panelists>
<panelist panelist_login="pradeep">
<login/>
<firstname/>
<lastname/>
<gender/>
<age>0</age>
</panelist>
<panelist panelist_login="kumar">
<login>kumar</login>
<firstname>kumar</firstname>
<lastname>Pradeep</lastname>
<gender/>
<age>24</age>
</panelist>
</panelists>
</project>
我用过的代码:
import xml.etree.ElementTree as ET
tree = ET.parse(xml_file.xml) # import xml from
root = tree.getroot()
Panelist_list = []
for item in root.findall('./panelists/panelist'): # find all projects node
Panelist = {} # dictionary to store content of each projects
panelist_login = {}
panelist_login = item.attrib
Panelist_list.append(panelist_login)
for child in item:
Panelist[child.tag] = child.text
Panelist_list.append(Panelist)
print(Panelist_list)
输出:
[{
'panelist_login': 'pradeep'
}, {
'login': None,
'firstname': None,
'lastname': None,
'gender': None,
'age': '0'
}, {
'panelist_login': 'kumar'
}, {
'login': 'kumar',
'firstname': 'kumar',
'lastname': 'Pradeep',
'gender': None,
'age': '24'
}]
我期待以下输出
[{
'panelist_login': 'pradeep',
'login': None,
'firstname': None,
'lastname': None,
'gender': None,
'age': '0'
}, {
'panelist_login': 'kumar'
'login': 'kumar',
'firstname': 'kumar',
'lastname': 'Pradeep',
'gender': None,
'age': '24'
}]
我已经在 xml 树上引用了很多堆栈溢出问题,但仍然没有帮助我。
任何帮助/建议表示赞赏。
解决方案
panelist_login
您的代码将带有标签属性的字典附加到列表中,在这一行中:与字典Panelist_list.append(panelist_login)
分开。Panelist
因此,对于每个<panelist>
标签,代码都会附加 2 个字典:一个标签属性字典和一个子标签字典。在循环内部,您有 2 个append()
调用,这意味着每次通过循环时列表中有 2 个项目。
但是您实际上希望每个标签都有一个 dict <panelist>
,并且您希望标签属性出现在dict 中,Panelist
就好像它也是一个子标签一样。
所以有一个字典,并Panelist
使用标签属性更新字典,而不是将标签属性保存在单独的字典中。
for item in root.findall('./panelists/panelist'): # find all projects node
Panelist = {} # dictionary to store content of each projects
panelist_login = item.attrib
Panelist.update(panelist_login) # make panelist_login the first key of the dict
for child in item:
Panelist[child.tag] = child.text
Panelist_list.append(Panelist)
print(Panelist_list)
我得到了这个输出,我认为这就是你的想法:
[
{'panelist_login': 'pradeep',
'login': None,
'firstname': None,
'lastname': None,
'gender': None,
'age': '0'},
{'panelist_login': 'kumar',
'login': 'kumar',
'firstname': 'kumar',
'lastname': 'Pradeep',
'gender': None,
'age': '24'}
]
推荐阅读
- python - 列不可迭代 - apache spark dataframe - python
- javascript - 与对象的角度,异步调用?
- unetstack - 关于UnetStack MAC层的发送和接收确认
- python - 如何使虚拟环境与 pyenv 一起工作?
- java - 使用 HashMap 添加/检索等
- r - GGplot 问题:连续值被解释为离散值,无法正确绘制
- reactjs - 在使用创建反应应用程序制作的现有项目中创建反应应用程序
- tcl - 如何从表达式中正确返回字符串常量?
- amazon-web-services - 拒绝访问将开放数据读入 Sagemaker
- macos - 将独立 Java 应用程序中的点连接到 Mac OS 安装