使用 xmltodict 解析 XML 后,使用 Python 字典访问键和值

问题描述 投票:0回答:1

给定 XML 文件:

<?xml version="1.0" standalone="yes"?>
<!--COUNTRIES is the root element-->
<WORLD>
    <country name="ABCDEF">
        <event day="323" name="$abcd"> </event>
        <event day="23" name="$aklm"> </event>

        <neighbor name="B" direction="W" friend="T"></neighbor>
        <neighbor name="C" direction="E"></neighbor>
        <neighbor name="D" direction="W"></neighbor>
    </country>
    <country name="KLMNOP">
        <event day="825" name="$nmre"> </event>
        <event day="329" name="$lpok"> </event>
        <event day="145" name="$dswq"> </event>
        <event day="256" name="$tyul"> </event>

        <neighbor name="D" direction="S"/>
        <neighbor name="E" direction="N" friend="T"/>
    </country>
</WORLD>

然后我使用 Python 中的“xmltodict”库解析了这个 xml 文件:

import xmltodict

class XMLParser:
    def __init__(self, xml_file_path):
        self.xml_file_path = xml_file_path
        if not self.xml_file_path:
            raise ValueError("XML file path is not found./n")
        
        with open (self.xml_file_path, 'r') as f:
            self.xml_file = f.read()

    def parse_xml_to_json(self):
        xml_file = self.xml_file
        dict = xmltodict.parse(xml_file, attr_prefix='')

        for k in dict['WORLD']['country'][1]:
            if k == "name":
                print(dict.keys())
                print(dict.values())

        return dict

xml_file_path = "file_path"
xml_parser = XMLParser(xml_file_path)
data = xml_parser.parse_xml_to_json()
print(data)

但是,我收到错误,无法从该字典访问键和值。

错误:AttributeError:“str”对象没有属性“keys”

我想获得以下格式的输出:

所需输出:

    { "neighbor":
[
{
  "Name": "B",
  "direction": "W",
  "Type": "ABCDEF"
},
{  
  "Name": "C",
  "direction": "E",
  "Type": "ABCDEF"
},
{  
  "Name": "D",
  "direction": "W",
  "Type": "ABCDEF"
},
{  
  "Name": "D",
  "direction": "S",
  "Type": "KLMNOP"
},
{  
  "Name": "E",
  "direction": "N",
  "Type": "KLMNOP"
},
]
}

请建议,我是 xml 和 python 的新手。

python json xml xml-parsing xmltodict
1个回答
0
投票

一个简单的嵌套循环可以在这里工作:

import xml.etree.ElementTree as ET

xml = '''<WORLD>
    <country name="ABCDEF">
        <event day="323" name="$abcd"> </event>
        <event day="23" name="$aklm"> </event>

        <neighbor name="B" direction="W" friend="T"></neighbor>
        <neighbor name="C" direction="E"></neighbor>
        <neighbor name="D" direction="W"></neighbor>
    </country>
    <country name="KLMNOP">
        <event day="825" name="$nmre"> </event>
        <event day="329" name="$lpok"> </event>
        <event day="145" name="$dswq"> </event>
        <event day="256" name="$tyul"> </event>

        <neighbor name="D" direction="S"/>
        <neighbor name="E" direction="N" friend="T"/>
    </country>
</WORLD>'''
data = {'neighbor': []}
root = ET.fromstring(xml)
for country in root.findall('.//country'):
    country_name = country.attrib['name']
    for neighbor in country.findall('neighbor'):
        data['neighbor'].append({'Type': country_name, 'Name': neighbor.attrib['name'],'direction': neighbor.attrib['direction']})
print(data)

输出

{
  'neighbor': [
    {
      'Type': 'ABCDEF',
      'Name': 'B',
      'direction': 'W'
    },
    {
      'Type': 'ABCDEF',
      'Name': 'C',
      'direction': 'E'
    },
    {
      'Type': 'ABCDEF',
      'Name': 'D',
      'direction': 'W'
    },
    {
      'Type': 'KLMNOP',
      'Name': 'D',
      'direction': 'S'
    },
    {
      'Type': 'KLMNOP',
      'Name': 'E',
      'direction': 'N'
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.