XML DOM 删除节点
全面讲解 XML DOM 中删除元素节点、通过 parentNode 删除自身、删除与清空文本节点的区别,以及使用 removeAttribute() 和 removeAttributeNode() 删除属性的方法。
学完这一章,你能够
- 全面讲解 XML DOM 中删除元素节点、通过 parentNode 删除自身、删除与清空文本节点的区别,以及使用 removeAttribute() 和 removeAttributeNode() 删除属性的方法。
删除元素节点与通过 parentNode 删除自身
在 XML DOM 中,删除子节点使用 `removeChild()` 方法,删除属性使用 `removeAttribute()` 或 `removeAttributeNode()` 方法。围绕 `books.xml`,典型操作涵盖六类场景:从根元素移除首个 `<book>`、通过 `parentNode` 删除当前节点、删除 `<title>` 的文本节点、通过 `nodeValue` 属性(注意 `nodeValue` 是属性而非方法)清空文本节点内容、按名称删除属性,以及按属性对象循环清空全部属性。
`removeChild(node)` 会从调用它的父节点中摘除指定子节点,同时连带移除该节点下的所有后代子节点。要删除 `books.xml` 中的第一个 `<book>`,先定位 `y = xmlDoc.getElementsByTagName("book")[0]`,再在根元素上调用 `xmlDoc.documentElement.removeChild(y)` 即可。
在传统 W3C DOM Level 1/2 中,`removeChild()` 必须由父节点调用,因此当代码只持有待删除节点 `x` 时,常用 `x.parentNode.removeChild(x)` 借由其父节点删除自身(在现代 WHATWG DOM 浏览器标准中,还新增了更简短的 `x.remove()` 便捷方法)。
删除文本节点与清空文本值的区别
`removeChild()` 同样可以用来移除元素下的文本节点:取第一个 `<title>` 元素 `x` 及其第一个子节点 `y = x.childNodes[0]`,调用 `x.removeChild(y)` 会把该文本子节点彻底从 `<title>` 中移除(此后 `x.childNodes.length` 变为 `0`)。不过在日常实践中,通常不必删掉文本节点本身,更常见的是直接清空其文本内容。
使用 `nodeValue` 属性清空文本更为直接:令 `x = xmlDoc.getElementsByTagName("title")[0].childNodes[0]` 并设置 `x.nodeValue = ""`,即可把首书标题置为空字符串,同时保留该文本节点占位(`childNodes.length` 仍为 `1`),后续若要再写入新文字依然可以直接赋值 `nodeValue`;放入循环中即可清空全部 `<title>` 的文本。
按名称与按对象删除属性节点
`removeAttribute(name)` 按属性名直接移除元素上的指定属性,例如对首个 `<book>` 调用 `x[0].removeAttribute("category")` 即可删掉 `category` 属性;遍历所有 `<book>` 逐一调用即可批量删除同名属性,而同一元素上的其他属性(如第四本书的 `cover`)保持不变。
`removeAttributeNode(attrNode)` 接收一个属性节点对象作为参数并将其移除(返回被移除的旧属性节点)。若要清空所有 `<book>` 上的全部属性,可在遍历每个 `<book>` 时使用 `while (x[i].attributes.length > 0)` 循环,每次取出索引 `0` 处的属性节点并传给 `removeAttributeNode()`——因为 `attributes` 集合实时收缩,用 `while` 持续移除首项直到长度为 `0` 能够避免 `for` 循环跳过元素的问题。
实测 removeChild 删除元素/自身/文本、nodeValue 清空及两种属性删除方式
展开查看收起
"""Offline XML DOM verification lab for Chapter 16 (nodes-remove)."""
import json
import sys
import xml.dom.minidom as minidom
from lxml import etree
VERSION = f"CPython {sys.version.split()[0]} + xml.dom.minidom + lxml {etree.__version__}"
BOOKS_XML = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>"""
def case_remove_element_and_self_via_parent():
doc1 = minidom.parseString(BOOKS_XML)
y = doc1.getElementsByTagName("book")[0]
removed1 = doc1.documentElement.removeChild(y)
remaining1 = [t.childNodes[0].nodeValue for t in doc1.getElementsByTagName("title")]
doc2 = minidom.parseString(BOOKS_XML)
x = doc2.getElementsByTagName("book")[0]
removed2 = x.parentNode.removeChild(x)
remaining2 = [t.childNodes[0].nodeValue for t in doc2.getElementsByTagName("title")]
lxml_root = etree.fromstring(doc2.toxml().encode("utf-8"))
expected = {
"removed_tag": "book",
"remaining_count": 3,
"remaining_titles": ["Harry Potter", "XQuery Kick Start", "Learning XML"],
"both_methods_equal": True,
"lxml_book_count": 3,
}
actual = {
"removed_tag": removed1.tagName,
"remaining_count": len(remaining1),
"remaining_titles": remaining1,
"both_methods_equal": remaining1 == remaining2 and removed2.tagName == "book",
"lxml_book_count": len(lxml_root.findall("book")),
}
return {
"name": "remove_element_and_self_via_parent",
"summary": "验证 documentElement.removeChild(y) 与 x.parentNode.removeChild(x) 删除元素节点及其全部子节点",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_remove_text_node_vs_clear_nodevalue():
doc1 = minidom.parseString(BOOKS_XML)
t1 = doc1.getElementsByTagName("title")[0]
t1.removeChild(t1.childNodes[0])
doc2 = minidom.parseString(BOOKS_XML)
t2 = doc2.getElementsByTagName("title")[0]
t2.childNodes[0].nodeValue = ""
expected = {
"after_remove_child_len": 0,
"after_clear_nodevalue_len": 1,
"cleared_text_value": "",
}
actual = {
"after_remove_child_len": len(t1.childNodes),
"after_clear_nodevalue_len": len(t2.childNodes),
"cleared_text_value": t2.childNodes[0].nodeValue,
}
return {
"name": "remove_text_node_vs_clear_nodevalue",
"summary": "对比 removeChild 删除文本节点(childNodes 归零)与 nodeValue='' 清空文本(保留空文本节点)的差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_remove_attribute_by_name():
doc = minidom.parseString(BOOKS_XML)
books = doc.getElementsByTagName("book")
books[0].removeAttribute("category")
first_has_cat = books[0].hasAttribute("category")
for b in books:
if b.hasAttribute("category"):
b.removeAttribute("category")
remaining_attrs = [b.attributes.length for b in books]
expected = {
"first_has_category": False,
"remaining_attr_counts": [0, 0, 0, 1],
"fourth_keeps_cover": "paperback",
}
actual = {
"first_has_category": first_has_cat,
"remaining_attr_counts": remaining_attrs,
"fourth_keeps_cover": books[3].getAttribute("cover"),
}
return {
"name": "remove_attribute_by_name",
"summary": "使用 removeAttribute('category') 删除单个及全部 book 的 category 属性,核对其他属性不受影响",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_remove_all_attribute_nodes_loop():
doc = minidom.parseString(BOOKS_XML)
books = doc.getElementsByTagName("book")
before_total = sum(b.attributes.length for b in books)
removed_names = []
for b in books:
while b.attributes.length > 0:
attnode = b.attributes.item(0)
old_att = b.removeAttributeNode(attnode)
removed_names.append(old_att.nodeName)
after_total = sum(b.attributes.length for b in books)
expected = {
"before_total_attrs": 5,
"after_total_attrs": 0,
"removed_count": 5,
}
actual = {
"before_total_attrs": before_total,
"after_total_attrs": after_total,
"removed_count": len(removed_names),
}
return {
"name": "remove_all_attribute_nodes_loop",
"summary": "在 while 循环中使用 removeAttributeNode 删除全部 book 元素的全部属性节点,总数从 5 归零",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_remove_element_and_self_via_parent(),
case_remove_text_node_vs_clear_nodevalue(),
case_remove_attribute_by_name(),
case_remove_all_attribute_nodes_loop(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 `el.attributes` 是实时更新的 `NamedNodeMap`,每删掉一个属性,后续属性的索引都会向前移动且 `length` 减 1;使用固定递增索引的 `for` 循环会漏删一半属性。