XML DOM 替换节点
讲解如何使用 replaceChild(newNode, oldNode) 替换整个元素子树,并对比文本节点局部替换方法 replaceData(offset, length, string) 与整体赋值 nodeValue 的适用场景。
学完这一章,你能够
- 讲解如何使用 replaceChild(newNode, oldNode) 替换整个元素子树,并对比文本节点局部替换方法 replaceData(offset, length, string) 与整体赋值 nodeValue 的适用场景。
使用 replaceChild() 替换元素节点
替换节点包含两个层面:用新节点替换整个已有节点使用 `replaceChild()`,替换文本节点内的文字则可使用 `replaceData()` 或直接修改 `nodeValue`。围绕 `books.xml`,本节重点演练替换第一个 `<book>` 元素节点及替换首书 `<title>` 文本内容。
`parent.replaceChild(newNode, oldNode)` 用 `newNode` 替换 `parent` 下已有的子节点 `oldNode`(并返回被换出的 `oldNode`)。演示流程先加载 `books.xml`,接着调用 `createElement("book")`、`createElement("title")` 与 `createTextNode("A Notebook")` 组装新子树——先把文本节点追加到 `<title>`,再把 `<title>` 追加到新 `<book>`——最后定位原来的首个 `<book>` 节点 `y`,在根元素上调用 `x.replaceChild(newNode, y)` 完成原地替换。
替换文本数据:replaceData() 与 nodeValue 对比
若只需对文本节点中的局部字符区间做精确替换,可调用 `CharacterData` 接口继承而来的 `replaceData(offset, length, string)` 方法,其三个参数依次为:`offset`(从 `0` 开始计数的起始替换偏移量)、`length`(要被替换掉的字符长度)以及 `string`(插入的新字符串)。对首书标题 `"Everyday Italian"` 执行 `x.replaceData(0, 8, "Easy")`,会用 `"Easy"` 替换前 8 个字符 `"Everyday"`,结果变为 `"Easy Italian"`。
当需要替换整个文本节点的内容而非计算局部下标时,直接给 `nodeValue` 赋值会更加简洁直观:取得首书 `<title>` 的文本节点 `x` 后,直接写入 `x.nodeValue = "Easy Italian"` 即可达到同等效果;更多改值用法可回顾前面“改变节点值”一章。
实测 replaceChild 替换 book 子树及 replaceData/nodeValue 替换文本数据
展开查看收起
"""Offline XML DOM verification lab for Chapter 17 (nodes-replace)."""
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_replace_element_node_with_replacechild():
doc = minidom.parseString(BOOKS_XML)
x = doc.documentElement
new_node = doc.createElement("book")
new_title = doc.createElement("title")
new_text = doc.createTextNode("A Notebook")
new_title.appendChild(new_text)
new_node.appendChild(new_title)
y = doc.getElementsByTagName("book")[0]
returned_old = x.replaceChild(new_node, y)
titles = [t.childNodes[0].nodeValue for t in doc.getElementsByTagName("title")]
expected = {
"returned_old_category": "cooking",
"book_count": 4,
"titles": ["A Notebook", "Harry Potter", "XQuery Kick Start", "Learning XML"],
}
actual = {
"returned_old_category": returned_old.getAttribute("category"),
"book_count": len(doc.getElementsByTagName("book")),
"titles": titles,
}
return {
"name": "replace_element_node_with_replacechild",
"summary": "使用 createElement/createTextNode 构造新 book 节点并调用 replaceChild(newNode, y) 替换首本书",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_replace_text_with_replacedata():
doc = minidom.parseString(BOOKS_XML)
x = doc.getElementsByTagName("title")[0].childNodes[0]
before = x.nodeValue
x.replaceData(0, 8, "Easy")
after = x.nodeValue
expected = {
"before": "Everyday Italian",
"after": "Easy Italian",
}
actual = {"before": before, "after": after}
return {
"name": "replace_text_with_replacedata",
"summary": "调用文本节点的 replaceData(0, 8, 'Easy') 将 'Everyday Italian' 前 8 字符替换为 'Easy'",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_replace_text_with_nodevalue():
doc = minidom.parseString(BOOKS_XML)
x = doc.getElementsByTagName("title")[0].childNodes[0]
x.nodeValue = "Easy Italian"
expected = {"node_value": "Easy Italian", "length": 12}
actual = {"node_value": x.nodeValue, "length": len(x.nodeValue)}
return {
"name": "replace_text_with_nodevalue",
"summary": "使用 nodeValue 直接整体替换文本节点内容为 'Easy Italian'",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_lxml_verify_replaced_tree():
doc = minidom.parseString(BOOKS_XML)
new_node = doc.createElement("book")
new_title = doc.createElement("title")
new_title.appendChild(doc.createTextNode("A Notebook"))
new_node.appendChild(new_title)
doc.documentElement.replaceChild(new_node, doc.getElementsByTagName("book")[0])
lxml_root = etree.fromstring(doc.toxml().encode("utf-8"))
lxml_titles = [el.text for el in lxml_root.findall("book/title")]
expected = ["A Notebook", "Harry Potter", "XQuery Kick Start", "Learning XML"]
actual = lxml_titles
return {
"name": "lxml_verify_replaced_tree",
"summary": "将 replaceChild 替换后的 XML 序列化并由 lxml.etree 解析核验书名序列",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_replace_element_node_with_replacechild(),
case_replace_text_with_replacedata(),
case_replace_text_with_nodevalue(),
case_lxml_verify_replaced_tree(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
第一个参数是新节点 `newNode`,第二个参数是待替换的旧子节点 `oldNode`;如果写反,DOM 会尝试在父节点下查找 `newNode` 并抛出 `NotFoundError` 异常。