"""Offline XML DOM verification lab for Chapter 30 (element)."""
import json
from xml.dom import Node, minidom
from lxml import etree
VERSION = "CPython 3.12.14 offline XML DOM verifier (xml.dom.minidom + lxml.etree)"
BOOK_XML = """<book xml:base="https://example.org/books/" xmlns="urn:books" xmlns:ed="urn:edition" id="b1" ed:code="E9">
<title>XML DOM</title><year>2005</year>
</book>"""
def elem_text_content(node) -> str:
parts = []
for c in node.childNodes:
if c.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
parts.append(c.data)
elif c.nodeType == Node.ELEMENT_NODE:
parts.append(elem_text_content(c))
return "".join(parts)
def case_element_text_child_and_node_props():
doc = minidom.parseString("<book><title>XML DOM</title><year>2005</year></book>")
book = doc.documentElement
title = book.firstChild
year = book.lastChild
expected = {
"year_tagName": "year",
"year_nodeName": "year",
"year_nodeType": 1,
"year_nodeValue_is_none": True,
"year_firstChild_type": 3,
"year_firstChild_value": "2005",
"year_parent_tag": "book",
"year_prev_tag": "title",
"title_next_tag": "year",
"year_owner_is_doc": True,
"book_textContent": "XML DOM2005",
}
actual = {
"year_tagName": year.tagName,
"year_nodeName": year.nodeName,
"year_nodeType": year.nodeType,
"year_nodeValue_is_none": year.nodeValue is None,
"year_firstChild_type": year.firstChild.nodeType,
"year_firstChild_value": year.firstChild.nodeValue,
"year_parent_tag": year.parentNode.tagName,
"year_prev_tag": year.previousSibling.tagName,
"title_next_tag": title.nextSibling.tagName,
"year_owner_is_doc": year.ownerDocument is doc,
"book_textContent": elem_text_content(book),
}
return {
"name": "element_text_child_and_node_props",
"summary": "验证 <year>2005</year> 文本存储在子文本节点中,以及 Element 继承自 Node 的核心导航属性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_element_attribute_crud_and_ns():
doc = minidom.parseString(BOOK_XML)
book = doc.documentElement
book.setAttribute("category", "tech")
has_cat = book.hasAttribute("category")
cat_val = book.getAttribute("category")
cat_node = book.getAttributeNode("category")
a_node = doc.createAttribute("edition")
a_node.value = "3rd"
book.setAttributeNode(a_node)
removed_node = book.removeAttributeNode(a_node)
book.setAttributeNS("urn:edition", "ed:status", "published")
ns_val = book.getAttributeNS("urn:edition", "status")
has_ns = book.hasAttributeNS("urn:edition", "status")
ns_node = book.getAttributeNodeNS("urn:edition", "status")
a_ns = doc.createAttributeNS("urn:edition", "ed:region")
a_ns.value = "APAC"
book.setAttributeNodeNS(a_ns)
book.removeAttributeNS("urn:edition", "region")
book.removeAttribute("category")
expected = {
"hasAttributes_initial": True,
"has_cat": True,
"cat_val": "tech",
"cat_node_name": "category",
"removed_node_value": "3rd",
"ns_val": "published",
"has_ns": True,
"ns_node_localName": "status",
"region_removed": True,
"cat_removed": True,
}
actual = {
"hasAttributes_initial": book.hasAttributes(),
"has_cat": has_cat,
"cat_val": cat_val,
"cat_node_name": cat_node.name,
"removed_node_value": removed_node.value,
"ns_val": ns_val,
"has_ns": has_ns,
"ns_node_localName": ns_node.localName,
"region_removed": not book.hasAttributeNS("urn:edition", "region"),
"cat_removed": not book.hasAttribute("category"),
}
return {
"name": "element_attribute_crud_and_ns",
"summary": "验证 Element 全套普通属性与命名空间属性读写、节点操作及删除方法",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_element_descendant_query_and_mutation():
doc = minidom.parseString(
'<shelf xmlns:bk="urn:books"><bk:item>A</bk:item><item>B</item></shelf>'
)
shelf = doc.documentElement
c = doc.createElement("item")
c.appendChild(doc.createTextNode("C1"))
c.appendChild(doc.createTextNode("C2"))
shelf.appendChild(c)
c.normalize()
d = doc.createElement("item")
d.appendChild(doc.createTextNode("D"))
shelf.insertBefore(d, c)
e = doc.createElement("item")
e.appendChild(doc.createTextNode("E"))
shelf.replaceChild(e, d)
shelf.removeChild(e)
c_copy = c.cloneNode(True)
shelf.appendChild(c_copy)
plain_items = shelf.getElementsByTagName("item")
ns_items = shelf.getElementsByTagNameNS("urn:books", "item")
expected = {
"has_children": True,
"normalized_c_text": "C1C2",
"plain_item_texts": ["B", "C1C2", "C1C2"],
"ns_item_texts": ["A"],
}
actual = {
"has_children": shelf.hasChildNodes(),
"normalized_c_text": c.firstChild.data,
"plain_item_texts": [el.firstChild.data for el in plain_items],
"ns_item_texts": [el.firstChild.data for el in ns_items],
}
return {
"name": "element_descendant_query_and_mutation",
"summary": "验证 Element 子树查询(TagName/TagNameNS)、增删改克隆与 normalize() 合并相邻文本节点",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_element_id_namespace_and_dom3_methods():
doc = minidom.parseString(BOOK_XML)
book = doc.documentElement
book.setIdAttribute("id")
book.setIdAttributeNS("urn:edition", "code")
custom_id = doc.createAttribute("uid")
custom_id.value = "U100"
book.setAttributeNode(custom_id)
book.setIdAttributeNode(custom_id)
lroot = etree.fromstring(BOOK_XML.encode("utf-8"))
nsmap = lroot.nsmap
expected = {
"get_by_id": True,
"get_by_ns_id": True,
"get_by_attr_node_id": True,
"localName": "book",
"namespaceURI": "urn:books",
"prefix_is_none": True,
"baseURI": "https://example.org/books/",
"lookup_ed_ns": "urn:edition",
"isSameNode_self": True,
"isSupported_xml": True,
}
actual = {
"get_by_id": doc.getElementById("b1") is book,
"get_by_ns_id": doc.getElementById("E9") is book,
"get_by_attr_node_id": doc.getElementById("U100") is book,
"localName": book.localName,
"namespaceURI": book.namespaceURI,
"prefix_is_none": book.prefix is None,
"baseURI": lroot.base,
"lookup_ed_ns": nsmap.get("ed"),
"isSameNode_self": book.isSameNode(book),
"isSupported_xml": doc.implementation.hasFeature("XML", "1.0"),
}
return {
"name": "element_id_namespace_and_dom3_methods",
"summary": "验证 setIdAttribute 系列方法、命名空间属性、baseURI 与 DOM Level 3 扩展接口语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_element_text_child_and_node_props(),
case_element_attribute_crud_and_ns(),
case_element_descendant_query_and_mutation(),
case_element_id_namespace_and_dom3_methods(),
]
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-element-lab/explore-element.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-element.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2758.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip