XML DOM 改变节点值
讲解如何通过修改子文本节点的 nodeValue 来改变元素文本,并对比使用 setAttribute() 与属性节点 nodeValue 两种方式改写或新增 XML 属性值。
学完这一章,你能够
- 讲解如何通过修改子文本节点的 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 覆盖与新增属性及属性节点改值
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
当属性原本不存在时,`getAttributeNode(name)` 返回 `null`/`None`,直接访问 `.nodeValue` 会触发空引用异常;而 `setAttribute()` 在属性不存在时会自动创建该属性。