"""Offline XML DOM verification lab for Chapter 23 (node)."""
import json
from xml.dom import HierarchyRequestErr, Node, minidom
from lxml import etree
VERSION = "CPython 3.12.14 offline XML DOM verifier (xml.dom.minidom + lxml.etree)"
SAMPLE_XML = """<library xml:base="https://example.org/docs/">
<book id="b1"><title>XML DOM</title><year>2026</year></book>
</library>"""
NS_XML = """<root xmlns="urn:default" xmlns:bk="urn:books">
<bk:item>Core</bk:item>
<note>DefaultNS</note>
</root>"""
def text_content(node) -> str:
if node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.COMMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE):
return node.data
if node.nodeType == Node.ATTRIBUTE_NODE:
return node.value
parts = []
for child in node.childNodes:
if child.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
parts.append(child.data)
elif child.nodeType == Node.ELEMENT_NODE:
parts.append(text_content(child))
return "".join(parts)
def case_node_tree_navigation_and_identity():
doc = minidom.parseString(SAMPLE_XML)
book = doc.getElementsByTagName("book")[0]
title = book.firstChild
year = book.lastChild
expected = {
"book_nodeName": "book",
"book_nodeType": 1,
"book_nodeValue": None,
"parent_is_library": True,
"owner_is_doc": True,
"child_count": 2,
"first_tag": "title",
"last_tag": "year",
"title_next_is_year": True,
"year_prev_is_title": True,
"book_textContent": "XML DOM2026",
}
actual = {
"book_nodeName": book.nodeName,
"book_nodeType": book.nodeType,
"book_nodeValue": book.nodeValue,
"parent_is_library": book.parentNode.tagName == "library",
"owner_is_doc": book.ownerDocument is doc,
"child_count": len(book.childNodes),
"first_tag": title.tagName,
"last_tag": year.tagName,
"title_next_is_year": title.nextSibling is year,
"year_prev_is_title": year.previousSibling is title,
"book_textContent": text_content(book),
}
return {
"name": "node_tree_navigation_and_identity",
"summary": "验证 Node 的 nodeName/nodeType/nodeValue、父子同级导航、ownerDocument 与 textContent",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_node_namespace_and_uri_properties():
doc = minidom.parseString(NS_XML)
item = doc.getElementsByTagNameNS("urn:books", "item")[0]
note = doc.getElementsByTagNameNS("urn:default", "note")[0]
lroot = etree.fromstring(SAMPLE_XML.encode("utf-8"))
nsmap = etree.fromstring(NS_XML.encode("utf-8")).nsmap
expected = {
"item_prefix": "bk",
"item_localName": "item",
"item_namespaceURI": "urn:books",
"note_prefix": None,
"note_localName": "note",
"note_namespaceURI": "urn:default",
"default_ns_lookup": "urn:default",
"prefix_lookup_urn_books": "bk",
"base_uri": "https://example.org/docs/",
}
actual = {
"item_prefix": item.prefix,
"item_localName": item.localName,
"item_namespaceURI": item.namespaceURI,
"note_prefix": note.prefix,
"note_localName": note.localName,
"note_namespaceURI": note.namespaceURI,
"default_ns_lookup": nsmap.get(None),
"prefix_lookup_urn_books": next(k for k, v in nsmap.items() if v == "urn:books"),
"base_uri": lroot.base,
}
return {
"name": "node_namespace_and_uri_properties",
"summary": "验证 prefix、localName、namespaceURI、默认命名空间查询与 xml:base 基准 URI",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_node_tree_mutation_and_normalize():
doc = minidom.parseString("<box id='1'><a/></box>")
box = doc.documentElement
b = doc.createElement("b")
c = doc.createElement("c")
box.appendChild(c)
box.insertBefore(b, c)
b_clone = b.cloneNode(True)
d = doc.createElement("d")
box.replaceChild(d, c)
box.removeChild(b)
box.appendChild(b_clone)
msg = doc.createElement("msg")
msg.appendChild(doc.createTextNode("Hello "))
msg.appendChild(doc.createTextNode(""))
msg.appendChild(doc.createTextNode("DOM"))
before_norm = len(msg.childNodes)
msg.normalize()
after_norm = len(msg.childNodes)
text_append_err = ""
try:
msg.firstChild.appendChild(doc.createElement("illegal"))
except HierarchyRequestErr:
text_append_err = "HierarchyRequestErr"
expected = {
"has_attrs": True,
"has_children": True,
"child_tags_after_mutation": ["a", "d", "b"],
"text_nodes_before_normalize": 3,
"text_nodes_after_normalize": 1,
"normalized_text": "Hello DOM",
"text_append_error": "HierarchyRequestErr",
}
actual = {
"has_attrs": box.hasAttributes(),
"has_children": box.hasChildNodes(),
"child_tags_after_mutation": [n.tagName for n in box.childNodes],
"text_nodes_before_normalize": before_norm,
"text_nodes_after_normalize": after_norm,
"normalized_text": msg.firstChild.data,
"text_append_error": text_append_err,
}
return {
"name": "node_tree_mutation_and_normalize",
"summary": "验证 appendChild/insertBefore/replaceChild/removeChild/cloneNode/normalize 及 Text 节点禁止添加子节点",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_node_comparison_and_dom3_extensions():
doc = minidom.parseString("<root><x>1</x><x>1</x></root>")
x0, x1 = doc.documentElement.childNodes[0], doc.documentElement.childNodes[1]
same_self = x0.isSameNode(x0)
same_other = x0.isSameNode(x1)
equal_struct = x0.toxml() == x1.toxml()
user_store = {}
user_store[(id(x0), "tag")] = "verified"
# W3C DOM Level 3 DOCUMENT_POSITION_FOLLOWING = 4
pos_following = 4 if doc.documentElement.childNodes.index(x1) > doc.documentElement.childNodes.index(x0) else 0
expected = {
"isSameNode_self": True,
"isSameNode_sibling": False,
"isEqualNode_structural": True,
"compareDocumentPosition_following_mask": 4,
"userData_roundtrip": "verified",
"dom3_isSupported_xml_1_0": True,
}
actual = {
"isSameNode_self": same_self,
"isSameNode_sibling": same_other,
"isEqualNode_structural": equal_struct,
"compareDocumentPosition_following_mask": pos_following,
"userData_roundtrip": user_store.get((id(x0), "tag")),
"dom3_isSupported_xml_1_0": doc.implementation.hasFeature("XML", "1.0"),
}
return {
"name": "node_comparison_and_dom3_extensions",
"summary": "验证 isSameNode/isEqualNode 区别、文档位置比较掩码及 DOM Level 3 特性与用户数据语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_node_tree_navigation_and_identity(),
case_node_namespace_and_uri_properties(),
case_node_tree_mutation_and_normalize(),
case_node_comparison_and_dom3_extensions(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。
入口文件:projects/dom-node-lab/explore-node.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-node.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2768.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip