"""Offline XML DOM verification lab for Chapter 10 (nodes-nodelist)."""
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_nodelist_index_and_first_title():
doc = minidom.parseString(BOOKS_XML)
x = doc.getElementsByTagName("title")
txt = x[0].childNodes[0].nodeValue
expected = {
"is_nodelist_type": True,
"first_title": "Everyday Italian",
"item_0_matches_index_0": True,
}
actual = {
"is_nodelist_type": type(x).__name__ == "NodeList",
"first_title": txt,
"item_0_matches_index_0": x.item(0) is x[0],
}
return {
"name": "nodelist_index_and_first_title",
"summary": "验证 getElementsByTagName 返回 NodeList,并通过 0 起始索引与 item(0) 读取首条 title 文本",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nodelist_length_and_iteration():
doc = minidom.parseString(BOOKS_XML)
x = doc.getElementsByTagName("title")
collected = [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": collected,
"matches_lxml": collected == lxml_titles,
}
return {
"name": "nodelist_length_and_iteration",
"summary": "核对 NodeList.length 为 4 并按 XML 文档出现顺序遍历输出全部 4 个书名",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nodelist_live_vs_snapshot_check():
doc = minidom.parseString("<bookstore><book><title>A</title></book></bookstore>")
live_children = doc.documentElement.childNodes
minidom_tag_list = doc.getElementsByTagName("title")
new_book = doc.createElement("book")
new_title = doc.createElement("title")
new_title.appendChild(doc.createTextNode("B"))
new_book.appendChild(new_title)
doc.documentElement.appendChild(new_book)
fresh_tag_list = doc.getElementsByTagName("title")
expected = {
"childnodes_live_updated_to_2": True,
"minidom_tag_snapshot_stayed_1": True,
"fresh_query_count": 2,
}
actual = {
"childnodes_live_updated_to_2": len(live_children) == 2,
"minidom_tag_snapshot_stayed_1": len(minidom_tag_list) == 1,
"fresh_query_count": len(fresh_tag_list),
}
return {
"name": "nodelist_live_vs_snapshot_check",
"summary": "实测 minidom 中 childNodes 实时动态更新,同时如实记录 minidom getElementsByTagName 返回快照(区别于浏览器 DOM 实时集合)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_named_node_map_attributes():
doc = minidom.parseString(BOOKS_XML)
book0 = doc.getElementsByTagName("book")[0]
x = book0.attributes
cat_val = x.getNamedItem("category").nodeValue
initial_len = x.length
book0.setAttribute("edition", "1st")
after_add_len = x.length
book0.removeAttribute("edition")
after_remove_len = x.length
expected = {
"map_type": "NamedNodeMap",
"category_value": "cooking",
"initial_length": 1,
"after_add_length": 2,
"after_remove_length": 1,
}
actual = {
"map_type": type(x).__name__,
"category_value": cat_val,
"initial_length": initial_len,
"after_add_length": after_add_len,
"after_remove_length": after_remove_len,
}
return {
"name": "named_node_map_attributes",
"summary": "验证 attributes 返回 NamedNodeMap,核对 getNamedItem('category').nodeValue、length 及增删属性时的自动更新",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_nodelist_index_and_first_title(),
case_nodelist_length_and_iteration(),
case_nodelist_live_vs_snapshot_check(),
case_named_node_map_attributes(),
]
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-nodelist-lab/explore-nodes-nodelist.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-nodes-nodelist.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2778.zip