首页 > 解决方案 > 在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 树上引用了很多堆栈溢出问题,但仍然没有帮助我。

任何帮助/建议表示赞赏。

标签: pythonxmldictionaryxml-parsing

解决方案


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

推荐阅读