答案:使用xml.etree.ElementTree可安全删除XML元素。先解析文件,通过findall查找目标元素,结合get或text匹配属性或文本,再调用父节点remove删除,最后write保存。注意仅能删除直接子节点,深层元素需定位至父级操作,遍历时避免直接修改列表。

在 Python 中操作 XML 文档并删除元素,通常使用内置的 xml.etree.ElementTree 模块。它提供了简单而有效的方式来解析、修改和保存 XML 文件。下面介绍如何安全地删除指定元素。
如果你只想删除某个父元素下的特定子元素,可以先找到该父元素,然后遍历其子节点,匹配后移除。
示例 XML 结构:<root> <item id="1"><name>A</name></item> <item id="2"><name>B</name></item> <item id="3"><name>C</name></item> </root>
删除 id="2" 的 item 元素:
import xml.etree.ElementTree as ET
<p>tree = ET.parse('data.xml')
root = tree.getroot()</p><h1>查找并删除 id="2" 的 item</h1><p>for item in root.findall('item'):
if item.get('id') == '2':
root.remove(item)</p><p>tree.write('data.xml', encoding='utf-8', xml_declaration=True)</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>你可以结合属性、文本或其他条件来决定是否删除元素。
例如:删除 name 文本为 "B" 的 item:
for item in root.findall('item'):
name_elem = item.find('name')
if name_elem is not None and name_elem.text == 'B':
root.remove(item)
如果要删除的元素不在根下,而是嵌套较深,建议使用路径查找,并从父节点中删除。
不能直接对 findall 返回的结果调用 remove,如果不在直接子节点层,需获取父节点:
# 删除所有 level2 下的 target 元素
for parent in root.findall('.//level2/..'):
for elem in parent.findall('level2'):
if elem.find('target') is not None:
parent.remove(elem)
或者更精确地定位:
# 删除路径为 './/category/item' 中满足条件的元素
for item in root.findall('.//category/item'):
if item.get('status') == 'inactive':
# 获取父节点并删除
parent = root.find('.//category') # 确保能定位到父级
if parent is not None and item in parent:
parent.remove(item)
基本上就这些。掌握 find、findall、get、remove 和 write 的组合,就能灵活处理大多数 XML 删除需求。
以上就是python中XML删除元素的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号