
使用 Python 的 xml.etree.ElementTree 删除 XML 元素时,直接通过索引 del root[i][j] 无法可靠移除节点,因其不触发父节点的结构更新;应改用 find() 定位目标元素后调用 parent.remove(child) 方法。
使用 python 的 `xml.etree.elementtree` 删除 xml 元素时,直接通过索引 `del root[i][j]` 无法可靠移除节点,因其不触发父节点的结构更新;应改用 `find()` 定位目标元素后调用 `parent.remove(child)` 方法。
在处理 XML 文档时,一个常见误区是认为 del 语句能像操作普通 Python 列表一样直接从 ElementTree 中“删除”子元素。实际上,root[1][1] 返回的是对某个
✅ 正确做法是:先精确定位目标元素,再显式调用其父节点的 remove() 方法。推荐使用 XPath 表达式(如 .//date/day[2])进行语义化查找,确保目标唯一且可维护:
import xml.etree.ElementTree as ET
xml_str = '''<homework name="stam">
<subject>
math
</subject>
<date>
<year>
2025
</year>
<day>
16.5
</day>
<day>
5.3
</day>
</date>
</homework>'''
root = ET.fromstring(xml_str)
# ✅ 步骤1:定位第二个 <day> 元素(XPath 索引从 1 开始)
day_to_remove = root.find(".//date/day[2]")
if day_to_remove is not None:
# ✅ 步骤2:获取其直接父节点(<date>),并执行 remove()
parent_date = day_to_remove.getparent() # 注意:getparent() 在标准 ElementTree 中不可用!
# ⚠️ 更兼容的写法:显式查找父节点
date_elem = root.find(".//date")
if date_elem is not None:
date_elem.remove(day_to_remove)
# 输出验证结果
ET.dump(root)? 关键说明:
- root.find(".//date/day[2]") 使用 XPath 定位第二个
(注意:XPath 中 [2] 表示第二个匹配项,而非零基索引); - Element.remove(child) 是 ElementTree 提供的唯一安全删除方法,它会从父节点的子节点列表中真正移除该元素,并维护树结构一致性;
- getparent() 方法在标准 xml.etree.ElementTree 中不可用(仅 lxml 支持),因此应避免依赖,改用 root.find() 显式获取父节点;
- 删除后建议调用 ET.tostring(root, encoding='unicode') 保存或验证结果,而非仅靠 ET.dump()(后者输出格式不规范,不适合生产环境)。
? 进阶提示:若需批量删除(如所有
# 删除所有 <day> 元素
for day in root.iterfind(".//date/day"):
root.find(".//date").remove(day)总之,XML 节点删除必须基于父子关系显式操作,切勿依赖索引删除。这是 ElementTree 设计的核心约定,也是保证解析器行为可预测、可维护的关键实践。

















