如何用Python解析XML转JSON后遍历嵌套对象并删改元素
问题描述
需要将给定XML文件转换为JSON,并完成两个修改:
- 删除所有
event元素 - 删除
country下neighbor节点的friend属性
给定XML内容:
<?xml version="1.0" standalone="yes"?> <!--COUNTRIES is the root element--> <WORLD> <country name="A"> <event day="323" name="$abcd"> </event> <event day="23" name="$aklm"> </event> <neighbor name="B" direction="W" friend="T"></neighbor> <neighbor name="B" direction="W"></neighbor> <neighbor name="B" direction="W"></neighbor> </country> <country name="C"> <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="N"/> <neighbor name="B" direction="W" friend="T"/> </country> </WORLD>
现有Python代码(使用xmltodict库,但未完成需求):
import xmltodict, 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_json(self): xml_file = self.xml_file json_data = xmltodict.parse(xml_file, attr_prefix='') if 'event' in json_data['WORLD']['country']: del json_data['WORLD']['country']['event'] return json.dumps(json_data, indent=4) xml_file_path = "file_path" xml_parser = XMLParser(xml_file_path) json_object = xml_parser.parse_xml_to_json() print(json_object)
解决方案
原代码问题点
- 当XML中有多个
country节点时,xmltodict会将json_data['WORLD']['country']解析为列表而非单个字典,原代码直接判断'event'是否存在会报错。 - 未处理
neighbor的friend属性,且neighbor同样可能是单个节点或列表节点。
修改后的代码
import xmltodict, 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.") with open(self.xml_file_path, 'r') as f: self.xml_file = f.read() def parse_xml_to_json(self): json_data = xmltodict.parse(self.xml_file, attr_prefix='') world_data = json_data['WORLD'] # 处理多个country节点,统一转为列表遍历 countries = world_data['country'] if not isinstance(countries, list): countries = [countries] for country in countries: # 删除当前country下的event元素(无论单个还是列表) country.pop('event', None) # 处理neighbor节点,统一转为列表遍历 neighbors = country.get('neighbor', []) if not isinstance(neighbors, list): neighbors = [neighbors] # 删除每个neighbor的friend属性 for neighbor in neighbors: neighbor.pop('friend', None) # 更新回原数据结构(如果原本是单个country,再转回去) if len(countries) == 1: world_data['country'] = countries[0] else: world_data['country'] = countries return json.dumps(json_data, indent=4) xml_file_path = "file_path" xml_parser = XMLParser(xml_file_path) json_object = xml_parser.parse_xml_to_json() print(json_object)
代码说明
- 统一将
country和neighbor转为列表处理,兼容单个或多个节点的情况 - 使用
dict.pop(key, None)安全删除元素/属性,避免KeyError - 最后还原country的结构(单个则转回字典,多个保持列表),保证输出结构和原XML对应
内容的提问来源于stack exchange,提问作者NaviB
相关产品推荐
相关产品推荐

