"""Offline XML DOM verification lab for Chapter 08 (nodes-access)."""
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>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</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_get_elements_by_tag_name_scope_and_index():
doc = minidom.parseString(BOOKS_XML)
all_titles = doc.getElementsByTagName("title")
first_book = doc.getElementsByTagName("book")[0]
scoped_titles = first_book.getElementsByTagName("title")
third_title = all_titles[2].childNodes[0].nodeValue
expected = {
"doc_title_count": 4,
"scoped_book0_title_count": 1,
"third_title_index_2": "XQuery Kick Start",
}
actual = {
"doc_title_count": len(all_titles),
"scoped_book0_title_count": len(scoped_titles),
"third_title_index_2": third_title,
}
return {
"name": "get_elements_by_tag_name_scope_and_index",
"summary": "对比文档级与局部元素级 getElementsByTagName 作用域,并按 0 起始索引访问第 3 个 title",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nodelist_length_loop_titles():
doc = minidom.parseString(BOOKS_XML)
x = doc.getElementsByTagName("title")
titles = [x[i].childNodes[0].nodeValue for i in range(x.length)]
lxml_titles = [el.text for el in etree.fromstring(BOOKS_XML.encode("utf-8")).findall(".//title")]
expected = {
"length": 4,
"titles": ["Everyday Italian", "Harry Potter", "XQuery Kick Start", "Learning XML"],
"matches_lxml": True,
}
actual = {
"length": x.length,
"titles": titles,
"matches_lxml": titles == lxml_titles,
}
return {
"name": "nodelist_length_loop_titles",
"summary": "使用节点列表的 length 属性循环输出全部 title 文本值,并用 lxml 核对一致",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_root_node_type_and_childnodes_loop():
doc = minidom.parseString(BOOKS_XML)
root = doc.documentElement
element_children = [
node.nodeName for node in root.childNodes if node.nodeType == 1
]
expected = {
"root_name": "bookstore",
"root_type": 1,
"raw_child_count": 9,
"element_child_names": ["book", "book", "book", "book"],
}
actual = {
"root_name": root.nodeName,
"root_type": root.nodeType,
"raw_child_count": len(root.childNodes),
"element_child_names": element_children,
}
return {
"name": "root_node_type_and_childnodes_loop",
"summary": "检查 documentElement 的 nodeName/nodeType,并遍历其 childNodes 过滤出 nodeType==1 的元素节点",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_sibling_navigation_with_nextsibling():
doc = minidom.parseString(BOOKS_XML)
book0 = doc.getElementsByTagName("book")[0]
names = []
y = book0.firstChild
for _ in range(len(book0.childNodes)):
if y.nodeType == 1:
names.append(y.nodeName)
y = y.nextSibling
expected = {
"element_names": ["title", "author", "year", "price"],
"ended_at_none": True,
}
actual = {
"element_names": names,
"ended_at_none": y is None,
}
return {
"name": "sibling_navigation_with_nextsibling",
"summary": "从第一个 book 的 firstChild 起沿 nextSibling 导航并按 nodeType==1 筛选子元素名",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_get_elements_by_tag_name_scope_and_index(),
case_nodelist_length_loop_titles(),
case_root_node_type_and_childnodes_loop(),
case_sibling_navigation_with_nextsibling(),
]
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-access-lab/explore-nodes-access.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-nodes-access.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2771.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip