使用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))
代码说明
- 移除原代码中无意义的测试逻辑,直接针对目标需求处理:
- 用
xmltodict.parse将XML转为字典,attr_prefix=''让XML属性直接成为字典键 - 遍历每个
country节点,提取国家名称作为Type字段值 - 对每个国家下的
neighbor节点,提取name(映射为Name)、direction字段,拼接成目标格式的字典 - 将所有邻国数据收集到
neighbor列表中,返回符合要求的结构
- 用
- 使用
json.dumps格式化输出,让结果更易读
注意事项
- 确保已安装xmltodict库:执行
pip install xmltodict - 代码中的
your_actual_file_path.xml需替换为你的XML文件真实路径
内容的提问来源于stack exchange,提问作者NaviB
相关产品推荐
相关产品推荐

