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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
会返回 `null`(在 Python `minidom` 中为 `None`),因此在读取 `doctype.name` 或 `doctype.systemId` 前应先做空值判断。