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

如何用Python解析XML转JSON后遍历嵌套对象并删改元素

问题描述

需要将给定XML文件转换为JSON,并完成两个修改:

  1. 删除所有event元素
  2. 删除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)
解决方案

原代码问题点

  1. 当XML中有多个country节点时,xmltodict会将json_data['WORLD']['country']解析为列表而非单个字典,原代码直接判断'event'是否存在会报错。
  2. 未处理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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:12:39