"""Offline XML DOM verification lab for Chapter 28 (documenttype)."""
import json
from io import StringIO
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.DTD)"
DTD_INTERNAL_XML = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ELEMENT note (to,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT body (#PCDATA)>
<!ENTITY brand "BlueSky">
<!NOTATION gif SYSTEM "image/gif">
]>
<note><to>Reader</to><body>Welcome to &brand;</body></note>
"""
def case_doctype_basic_properties():
impl = minidom.getDOMImplementation()
dt = impl.createDocumentType("note", "-//MBSKY//DTD Note 1.0//EN", "note.dtd")
doc_with_dt = impl.createDocument(None, "note", dt)
doc_without_dt = minidom.parseString("<note/>")
expected = {
"nodeType": 10,
"name": "note",
"nodeName": "note",
"publicId": "-//MBSKY//DTD Note 1.0//EN",
"systemId": "note.dtd",
"without_doctype_is_none": True,
}
actual = {
"nodeType": doc_with_dt.doctype.nodeType,
"name": doc_with_dt.doctype.name,
"nodeName": doc_with_dt.doctype.nodeName,
"publicId": doc_with_dt.doctype.publicId,
"systemId": doc_with_dt.doctype.systemId,
"without_doctype_is_none": doc_without_dt.doctype is None,
}
return {
"name": "doctype_basic_properties",
"summary": "验证 DocumentType 的 nodeType(10)、name、publicId、systemId 及无 DOCTYPE 时返回 None",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_doctype_internal_subset_and_entities():
parser = etree.XMLParser(load_dtd=True, resolve_entities=True)
root = etree.fromstring(DTD_INTERNAL_XML.encode("utf-8"), parser=parser)
info = root.getroottree().docinfo
internal = info.internalDTD
entity_names = [e.name for e in internal.entities()]
# Also verify minidom's NamedNodeMap attributes on DocumentType
dom_doc = minidom.parseString(DTD_INTERNAL_XML)
dt = dom_doc.doctype
has_entities_map = hasattr(dt, "entities") and dt.entities is not None
has_notations_map = hasattr(dt, "notations") and dt.notations is not None
# Validate DTD structure with lxml.etree.DTD
dtd_text = """
<!ELEMENT note (to,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT body (#PCDATA)>
"""
dtd = etree.DTD(StringIO(dtd_text))
valid_ok = dtd.validate(root)
expected = {
"doctype_root_name": "note",
"entity_names": ["brand"],
"expanded_body": "Welcome to BlueSky",
"has_entities_map": True,
"has_notations_map": True,
"dtd_validates_doc": True,
}
actual = {
"doctype_root_name": info.root_name,
"entity_names": entity_names,
"expanded_body": root.findtext("body"),
"has_entities_map": has_entities_map,
"has_notations_map": has_notations_map,
"dtd_validates_doc": valid_ok,
}
return {
"name": "doctype_internal_subset_and_entities",
"summary": "验证内部 DTD 子集、实体声明展开、notations/entities 映射与 DTD 结构校验",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_doctype_null_children_and_readonly():
impl = minidom.getDOMImplementation()
dt = impl.createDocumentType("doc", "", "doc.dtd")
doc = impl.createDocument(None, "doc", dt)
append_error = ""
try:
dt.appendChild(doc.createElement("x"))
except HierarchyRequestErr:
append_error = "HierarchyRequestErr"
expected = {
"nodeValue_is_none": True,
"has_children": False,
"append_child_error": "HierarchyRequestErr",
"nodeType_const": Node.DOCUMENT_TYPE_NODE,
}
actual = {
"nodeValue_is_none": dt.nodeValue is None,
"has_children": dt.hasChildNodes(),
"append_child_error": append_error,
"nodeType_const": dt.nodeType,
}
return {
"name": "doctype_null_children_and_readonly",
"summary": "验证 DocumentType 的 nodeValue 为 None 且不允许挂载子节点",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_doctype_basic_properties(),
case_doctype_internal_subset_and_entities(),
case_doctype_null_children_and_readonly(),
]
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-documenttype-lab/explore-documenttype.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-documenttype.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2757.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip