"""Offline XML DOM verification lab for Chapter 26 (document)."""
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)"
DOC_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd">
<catalog xmlns:bk="urn:books">
<bk:item code="A1">DOM Guide</bk:item>
<item code="B2">XML Core</item>
</catalog>
"""
def case_document_root_and_metadata_props():
doc = minidom.parseString(DOC_XML)
ltree = etree.fromstring(DOC_XML.encode("utf-8")).getroottree()
info = ltree.docinfo
expected = {
"nodeType": 9,
"nodeName": "#document",
"nodeValue_is_none": True,
"root_tag": "catalog",
"doctype_name": "catalog",
"has_implementation": True,
"firstChild_is_doctype": True,
"lastChild_is_root": True,
"xmlVersion": "1.0",
"xmlEncoding": "UTF-8",
"xmlStandalone": True,
}
actual = {
"nodeType": doc.nodeType,
"nodeName": doc.nodeName,
"nodeValue_is_none": doc.nodeValue is None,
"root_tag": doc.documentElement.tagName,
"doctype_name": doc.doctype.name if doc.doctype else None,
"has_implementation": doc.implementation is not None,
"firstChild_is_doctype": doc.firstChild is doc.doctype,
"lastChild_is_root": doc.lastChild is doc.documentElement,
"xmlVersion": info.xml_version,
"xmlEncoding": info.encoding,
"xmlStandalone": info.standalone,
}
return {
"name": "document_root_and_metadata_props",
"summary": "验证 Document 节点身份、documentElement/doctype/implementation、首尾子节点与 XML 声明元数据",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_document_factory_methods():
doc = minidom.getDOMImplementation().createDocument(None, "root", None)
el = doc.createElement("entry")
el_ns = doc.createElementNS("urn:demo", "d:meta")
attr = doc.createAttribute("role")
attr.value = "primary"
attr_ns = doc.createAttributeNS("urn:demo", "d:rev")
attr_ns.value = "3"
txt = doc.createTextNode("hello")
cdata = doc.createCDATASection("<raw/>")
cmt = doc.createComment("memo")
frag = doc.createDocumentFragment()
pi = doc.createProcessingInstruction("target", "k=v")
created = [el, el_ns, attr, attr_ns, txt, cdata, cmt, frag, pi]
expected = {
"all_owned_by_doc": True,
"node_types": [1, 1, 2, 2, 3, 4, 8, 11, 7],
"ns_element_uri": "urn:demo",
"ns_attr_localName": "rev",
}
actual = {
"all_owned_by_doc": all(n.ownerDocument is doc for n in created),
"node_types": [n.nodeType for n in created],
"ns_element_uri": el_ns.namespaceURI,
"ns_attr_localName": attr_ns.localName,
}
return {
"name": "document_factory_methods",
"summary": "验证 Document 全部节点工厂方法及所创建节点的 ownerDocument 归属关系",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_document_query_methods():
doc = minidom.parseString(DOC_XML)
all_items = doc.getElementsByTagName("item")
ns_items = doc.getElementsByTagNameNS("urn:books", "item")
first_ns = ns_items[0]
first_ns.setIdAttribute("code")
found_by_id = doc.getElementById("A1")
missing_by_id = doc.getElementById("NO_SUCH_ID")
expected = {
"plain_item_count": 1,
"ns_item_count": 1,
"ns_item_text": "DOM Guide",
"found_by_id_tag": "bk:item",
"missing_by_id_is_none": True,
}
actual = {
"plain_item_count": len(all_items),
"ns_item_count": len(ns_items),
"ns_item_text": ns_items[0].firstChild.data,
"found_by_id_tag": found_by_id.tagName if found_by_id else None,
"missing_by_id_is_none": missing_by_id is None,
}
return {
"name": "document_query_methods",
"summary": "验证 getElementsByTagName、getElementsByTagNameNS 与 getElementById 查询行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_document_cross_doc_and_rename():
src = minidom.parseString("<src><card><label>One</label></card></src>")
dst = minidom.parseString("<dst/>")
src_card = src.getElementsByTagName("card")[0]
shallow_imp = dst.importNode(src_card, False)
deep_imp = dst.importNode(src_card, True)
dst.documentElement.appendChild(deep_imp)
renamed = dst.renameNode(deep_imp, None, "itemCard")
renamed.appendChild(dst.createTextNode("A"))
renamed.appendChild(dst.createTextNode("B"))
before_norm = len(renamed.childNodes)
dst.normalize()
after_norm = len(renamed.childNodes)
expected = {
"shallow_has_children": False,
"deep_has_children": True,
"imported_owner_is_dst": True,
"source_still_owned_by_src": True,
"renamed_tag": "itemCard",
"children_before_normalize": 3,
"children_after_normalize": 2,
}
actual = {
"shallow_has_children": shallow_imp.hasChildNodes(),
"deep_has_children": deep_imp.hasChildNodes(),
"imported_owner_is_dst": deep_imp.ownerDocument is dst,
"source_still_owned_by_src": src_card.ownerDocument is src,
"renamed_tag": renamed.tagName,
"children_before_normalize": before_norm,
"children_after_normalize": after_norm,
}
return {
"name": "document_cross_doc_and_rename",
"summary": "验证跨文档 importNode(deep=False/True)、renameNode 重命名与文档规范化效果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_document_root_and_metadata_props(),
case_document_factory_methods(),
case_document_query_methods(),
case_document_cross_doc_and_rename(),
]
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-document-lab/explore-document.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-document.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2755.zip