DOM DocumentType
介绍 XML 文档类型声明接口 DocumentType 的作用与只读特征,详解 entities、internalSubset、name、notations 与 systemId 五项核心属性(并补充 publicId)。
学完这一章,你能够
- 介绍 XML 文档类型声明接口 DocumentType 的作用与只读特征,详解 entities、internalSubset、name、notations 与 systemId 五项核心属性(并补充 publicId)。
DocumentType 对象与文档类型声明
每个 XML `Document` 都拥有一个 `doctype` 属性:如果文档不包含 `<!DOCTYPE ...>` 声明,该属性值为 `null`;如果包含声明,则返回一个 `DocumentType` 对象(`nodeType === 10`)。在 W3C DOM Core 设计中,`DocumentType` 为程序访问 XML 文档关联的 DTD 名称、外部标识符以及 DTD 中定义的实体与符号声明提供了统一接口。
DocumentType 对象属性说明
`DocumentType` 节点不能拥有子节点且 `nodeValue` 恒为 `null`,其暴露的属性均为只读元数据。除源表列出的 `entities`、`internalSubset`、`name`、`notations` 和 `systemId` 五项外,规范中还包含 `publicId`(外部 DTD 公共标识符)。需要留意:在现代 DOM Living Standard 中仅保留了 `name`、`publicId` 和 `systemId` 三项属性,而 `entities`、`notations` 与 `internalSubset` 属于历史 DOM Level 2/3 接口,在服务端 XML 解析库(如 `lxml.etree`、`xml.dom.minidom`)中仍可结合 DTD 解析器访问。
DocumentType 对象属性参考
| 属性 | 返回类型与说明 |
|---|---|
| entities | 历史 DOM Core 只读属性:返回包含 DTD 中所声明一般实体的 `NamedNodeMap`。 |
| internalSubset | 历史 DOM Level 2/3 只读属性:以字符串形式返回内联声明在文档中的内部 DTD 子集,不存在时为 `null`。 |
| name | 只读字符串;返回 DOCTYPE 声明的名称(即 `<!DOCTYPE` 后紧跟的文档根元素名)。 |
| notations | 历史 DOM Core 只读属性:返回包含 DTD 中所声明 `<!NOTATION ...>` 符号的 `NamedNodeMap`。 |
| systemId | 只读字符串;返回外部 DTD 子集的系统标识符(URL/文件路径),无外部 DTD 时为空字符串或 `null`。 |
离线验证 DocumentType 属性、内部 DTD 实体展开与叶子节点只读约束
"""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()
- 离线验证器通过全部 3 项用例:核验 nodeType=10、name/publicId/systemId 与无 DOCTYPE 时为 None;通过 lxml.etree 与 minidom 验证内部 DTD 实体展开及 DTD 校验;确认 DocumentType 拒绝挂载子节点。
所需环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。
当前源码 SHA256:b36b03d75db8b9d6c7ae99cdab666c7c108750ed9655451510a437a6088c69d1
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。
ZIP SHA256:8d9bb51691ba1d26ee1cf5b57d05686668409c0c517ceabb6eb198c5b8d1d43d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
当一份 XML 文档没有写 `<!DOCTYPE ...>` 声明时,访问 `xmlDoc.doctype` 会返回什么结果?
展开参考解答
会返回 `null`(在 Python `minidom` 中为 `None`),因此在读取 `doctype.name` 或 `doctype.systemId` 前应先做空值判断。