蓝色天空网mbsky.com · 知识 · 实践 · 创造XML DOM · 本地阅读预览
教程 / XML / Web Service / XML DOM

XML DOM 替换节点

讲解如何使用 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 替换文本数据

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 确认 replaceChild 用 A Notebook 替换首本书并保持 4 本书总数,replaceData(0, 8, 'Easy') 与 nodeValue 均产出 Easy Italian,lxml 复验通过。
实测 replaceChild 替换 book 子树及 replaceData/nodeValue 替换文本数据

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

当前源码 SHA256:cd3141867f9b2f45ff157ca5e4a8f9aaa41aa579797591c039b1a98b75490159

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载XML DOM 替换节点实验

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

ZIP SHA256:a33ad52615c81eaa3f2ef6e64955fd1e9426f3e15f0caed333b72aa62ea043f3

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

`replaceChild(newNode, oldNode)` 的两个参数顺序是什么?写反会导致什么结果?

展开参考解答

第一个参数是新节点 `newNode`,第二个参数是待替换的旧子节点 `oldNode`;如果写反,DOM 会尝试在父节点下查找 `newNode` 并抛出 `NotFoundError` 异常。

规范与官方依据