"""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()
本例需在 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
入口文件:projects/dom-nodes-set-lab/explore-nodes-set.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-nodes-set.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2781.zip