如何删除XML树所有country节点中的指定子元素?
批量删除XML中所有country节点的指定子元素
原始XML文件
<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> <description>Liechtenstein has a lot of flowers.</description> </country> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> <description>Singapore has a lot of street markets.</description> </country> <country name="Panama"> <rank>68</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> <description>Panama has a lot of great food.</description> </country> </data>
现有参考代码
1. 删除满足条件的整个country节点
# 删除满足条件的country节点 for country in root.findall('country'): year = int(country.find('year').text) if year > 2010: root.remove(country) tree.write('sample.xml')
2. 删除单个country节点内指定子元素
# 删除单个匹配条件的子元素 for country in root.findall('country'): description_node = country.find('description') if description_node.text == "Singapore has a lot of street markets.": country.remove(description_node) tree.write('sample.xml')
解决方案
要实现批量删除所有country节点中的指定子元素,可以通过遍历所有country节点,对每个节点下的目标子元素(支持多个同名标签,如多个neighbor)进行批量删除。以下是完整代码:
import xml.etree.ElementTree as ET # 加载XML文件 tree = ET.parse('sample.xml') root = tree.getroot() # 定义需要删除的子元素标签列表 tags_to_remove = ['year', 'description', 'neighbor'] # 遍历所有country节点 for country in root.findall('country'): # 逐个处理要删除的标签 for tag in tags_to_remove: # 获取当前country下所有该标签的子节点 for element in country.findall(tag): country.remove(element) # 保存修改后的XML文件(保留XML声明和UTF-8编码) tree.write('modified_sample.xml', encoding='utf-8', xml_declaration=True)
代码说明
- 先加载目标XML文件并获取根节点
<data>; - 定义需要删除的子元素标签列表,可根据需求灵活调整;
- 遍历每个
<country>节点,对每个目标标签,用findall()获取该节点下所有对应子元素,逐个调用remove()删除; - 最后保存修改后的XML,指定编码和XML声明确保格式规范。
这种方法会处理所有country节点,不管子元素内容是什么,只要标签匹配就会被删除,同时支持删除多个同名子元素(如Liechtenstein和Panama的多个neighbor节点)。
内容的提问来源于stack exchange,提问作者joemamah24
相关产品推荐
相关产品推荐

