You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用xmltodict解析XML遇字典键值访问错误,需生成指定邻居数据格式

XML解析错误修复与目标格式转换方案

错误原因说明

你遇到的AttributeError: 'str' object has no attribute 'keys',是因为原代码中的遍历逻辑完全偏离需求,且存在逻辑误用:for k in dict['WORLD']['country'][1]会遍历第二个country字典的键名(如name、event),若误将字符串类型的键值当作字典操作,就会触发该错误。

修正后的完整代码

import xmltodict
import json

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_target_format(self):
        # 解析XML为字典,attr_prefix=''让属性直接作为键
        parsed_data = xmltodict.parse(self.xml_file, attr_prefix='')
        result = {"neighbor": []}
        
        # 遍历每个国家节点
        for country in parsed_data['WORLD']['country']:
            country_name = country['name']
            # 遍历当前国家的所有邻国节点
            for neighbor in country['neighbor']:
                # 构造目标格式的字典
                neighbor_item = {
                    "Name": neighbor['name'],
                    "direction": neighbor['direction'],
                    "Type": country_name
                }
                result["neighbor"].append(neighbor_item)
        
        return result

# 替换为你的实际XML文件路径
xml_file_path = "your_actual_file_path.xml"
xml_parser = XMLParser(xml_file_path)
target_data = xml_parser.parse_xml_to_target_format()
# 格式化输出结果
print(json.dumps(target_data, indent=2))

代码说明

  • 移除原代码中无意义的测试逻辑,直接针对目标需求处理:
    1. 用xmltodict.parse将XML转为字典,attr_prefix=''让XML属性直接成为字典键
    2. 遍历每个country节点,提取国家名称作为Type字段值
    3. 对每个国家下的neighbor节点,提取name(映射为Name)、direction字段,拼接成目标格式的字典
    4. 将所有邻国数据收集到neighbor列表中,返回符合要求的结构
  • 使用json.dumps格式化输出,让结果更易读

注意事项

  • 确保已安装xmltodict库:执行pip install xmltodict
  • 代码中的your_actual_file_path.xml需替换为你的XML文件真实路径

内容的提问来源于stack exchange,提问作者NaviB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:05:07