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

XML DOM 改变节点值

讲解如何通过修改子文本节点的 nodeValue 来改变元素文本,并对比使用 setAttribute() 与属性节点 nodeValue 两种方式改写或新增 XML 属性值。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

改变元素文本:修改子文本节点的 nodeValue

在 XML DOM 中,改变文本节点的值主要通过 `nodeValue` 属性完成,而修改或新增属性值通常使用 `setAttribute()` 方法(或属性节点的 `nodeValue`)。围绕 `books.xml`,典型练习包括修改第一个 `<title>` 的文本节点,以及分别用 `setAttribute()` 和 `nodeValue` 修改第一个 `<book>` 的 `category` 属性。

因为元素节点本身没有文本值,其文字保存在子文本节点中,所以要改变元素显示的文本,必须先找到对应的文本子节点再更新其 `nodeValue`:执行 `x = xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.nodeValue = "Easy Cooking";` 即可将首本书名改为 `"Easy Cooking"`。同理,在循环中遍历所有 `<title>` 元素即可批量改写全部标题。

改变属性值:setAttribute() 与属性节点 nodeValue

属性节点与元素节点不同,本身直接持有文本值,因此既可以调用所属元素的 `setAttribute(name, value)` 方法,也可以先拿到属性节点对象再修改其 `nodeValue` 属性。

`setAttribute(name, value)` 兼具“更新已有属性”和“创建不存在属性”两种语义:对 `books.xml` 中的第一个 `<book>` 执行 `x[0].setAttribute("category", "food")`,会将原有的 `"cooking"` 覆盖为 `"food"`;如果遍历所有 `<title>` 元素并设置一个尚不存在的属性(例如 `edition`),`setAttribute()` 会自动创建该新属性并赋予指定值。

若已通过 `getAttributeNode()` 取得属性节点对象,也可直接赋值给其 `nodeValue`:先取出第一个 `<book>` 的 `category` 属性节点 `y = x.getAttributeNode("category")`,再执行 `y.nodeValue = "food"`,同样完成原地更新(前提是该属性节点已经存在,否则 `y` 为 `null`/`None`)。

实测 nodeValue 改写元素文本、setAttribute 覆盖与新增属性及属性节点改值

python · 阅读源码
"""Offline XML DOM verification lab for Chapter 15 (nodes-set)."""
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_change_title_text_node_value():
    doc = minidom.parseString(BOOKS_XML)
    t0 = doc.getElementsByTagName("title")[0].childNodes[0]
    t0.nodeValue = "Easy Cooking"
    first_after = doc.getElementsByTagName("title")[0].childNodes[0].nodeValue
    for idx, el in enumerate(doc.getElementsByTagName("title"), 1):
        el.childNodes[0].nodeValue = f"Book {idx}"
    batch_after = [el.childNodes[0].nodeValue for el in doc.getElementsByTagName("title")]
    expected = {
        "first_after": "Easy Cooking",
        "batch_after": ["Book 1", "Book 2", "Book 3", "Book 4"],
    }
    actual = {
        "first_after": first_after,
        "batch_after": batch_after,
    }
    return {
        "name": "change_title_text_node_value",
        "summary": "使用 nodeValue 修改首书 title 文本为 Easy Cooking,并验证遍历批量改写所有 title 文本节点",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_set_attribute_update_and_create():
    doc = minidom.parseString(BOOKS_XML)
    books = doc.getElementsByTagName("book")
    books[0].setAttribute("category", "food")
    for title in doc.getElementsByTagName("title"):
        title.setAttribute("edition", "first")
    expected = {
        "updated_category": "food",
        "title_editions": ["first", "first", "first", "first"],
    }
    actual = {
        "updated_category": books[0].getAttribute("category"),
        "title_editions": [t.getAttribute("edition") for t in doc.getElementsByTagName("title")],
    }
    return {
        "name": "set_attribute_update_and_create",
        "summary": "验证 setAttribute 既可覆盖已有属性(category->food),也可在属性不存在时创建新属性(edition=first)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_change_attribute_via_node_value():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    attr_node = book0.getAttributeNode("category")
    before = attr_node.nodeValue
    attr_node.nodeValue = "food"
    expected = {
        "before": "cooking",
        "after_attr_node": "food",
        "after_get_attribute": "food",
    }
    actual = {
        "before": before,
        "after_attr_node": attr_node.nodeValue,
        "after_get_attribute": book0.getAttribute("category"),
    }
    return {
        "name": "change_attribute_via_node_value",
        "summary": "通过 getAttributeNode('category').nodeValue='food' 原地修改属性节点值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lxml_verify_serialized_mutations():
    doc = minidom.parseString(BOOKS_XML)
    doc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "Easy Cooking"
    doc.getElementsByTagName("book")[0].setAttribute("category", "food")
    lxml_root = etree.fromstring(doc.toxml().encode("utf-8"))
    book0 = lxml_root.find("book")
    expected = {"category": "food", "title": "Easy Cooking"}
    actual = {"category": book0.get("category"), "title": book0.findtext("title")}
    return {
        "name": "lxml_verify_serialized_mutations",
        "summary": "将文本与属性修改结果序列化为 XML 并由 lxml.etree 解析核验",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_change_title_text_node_value(),
        case_set_attribute_update_and_create(),
        case_change_attribute_via_node_value(),
        case_lxml_verify_serialized_mutations(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 确认首书 title 文本成功改为 Easy Cooking、setAttribute 同步验证更新与创建双语义,getAttributeNode('category').nodeValue='food' 生效且经 lxml 复验。
实测 nodeValue 改写元素文本、setAttribute 覆盖与新增属性及属性节点改值

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

当前源码 SHA256:f7232d91559a0a27e145f0bfdb9eb43e21223fef2efa1dc1d389b26cfb47b340

下载本站示例源码

本地运行

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

下载XML DOM 改变节点值实验

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

ZIP SHA256:6332c60497a8c572563ec491d28fa224b88c0ed00d952e45bc6f7747b7dc19fc

常见错误与边界

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

练习与解答

为什么修改属性时 `setAttribute(name, value)` 通常比 `getAttributeNode(name).nodeValue = value` 更安全?

展开参考解答

当属性原本不存在时,`getAttributeNode(name)` 返回 `null`/`None`,直接访问 `.nodeValue` 会触发空引用异常;而 `setAttribute()` 在属性不存在时会自动创建该属性。

规范与官方依据