DOM Document
全面梳理 XML DOM 根节点 Document 对象的顶层入口职责、节点工厂模式与 ownerDocument 绑定关系,并详述 17 项核心属性与 17 项创建/查询/跨文档导入方法。
学完这一章,你能够
- 全面梳理 XML DOM 根节点 Document 对象的顶层入口职责、节点工厂模式与 ownerDocument 绑定关系,并详述 17 项核心属性与 17 项创建/查询/跨文档导入方法。
Document 对象的顶层入口与节点工厂职责
`Document` 对象代表整份 XML 文档,是整棵 DOM 树的根节点(`nodeType === 9`、`nodeName === "#document"`),也是程序访问和检索文档数据的顶层入口。
由于元素、属性、文本、注释、CDATA 与处理指令等节点不能脱离文档上下文凭空存在,`Document` 同时承担“节点工厂”职责,提供一整套 `create*()` 工厂方法。每个由文档创建的节点都会通过 `ownerDocument` 属性指向其所属的 `Document` 实例;若需将节点迁移到另一份文档,必须先调用 `importNode()` 或 `adoptNode()`。
Document 对象属性与方法参考
下表完整列出了 `Document` 的 17 项属性与 17 项方法。需要特别留意几处历史与现代规范差异:`async`、`domConfig`、`strictErrorChecking`、`xmlEncoding`、`xmlStandalone`、`xmlVersion`、`createEntityReference()`、`normalizeDocument()` 及 `renameNode()` 源自早期 DOM Level 3 / 浏览器私有扩展,在现代 Web DOM Living Standard 中已被移除或废弃;而 `documentElement`、`doctype`、`implementation`、各类 `create*()` 工厂、`getElementById()`、`getElementsByTagName*()`、`importNode()` 与 `adoptNode()` 仍是现代标准的核心能力。针对原表中 `normalizeDocument()` 描述留空的问题,本表已依据 W3C DOM Level 3 Core 规范补全其准确定义(按 `domConfig` 配置对整份文档执行规范化,等同于保存后重新加载的效果)。
Document 对象属性参考
| 属性 | 作用与规范说明 |
|---|---|
| async | 历史扩展属性:指定旧式 `document.load()` 加载 XML 文件时是否采用异步模式(现代浏览器已移除)。 |
| childNodes | 只读;返回文档顶层子节点列表(可包含根元素、DOCTYPE、注释与处理指令)。 |
| doctype | 只读;返回与文档关联的 `DocumentType`(DTD)对象,无声明时为 `null`。 |
| documentElement | 只读;返回 XML 文档的唯一根元素节点(`Element`)。 |
| documentURI | 返回文档位置 URI(在 DOM Level 3 可读写,现代 DOM 为只读)。 |
| domConfig | 历史 DOM Level 3 属性:返回调用 `normalizeDocument()` 时使用的 `DOMConfiguration` 对象(现代已移除)。 |
| firstChild | 只读;返回文档的第一个子节点(可能是 `DocumentType`、注释、处理指令或根元素)。 |
| implementation | 只读;返回负责处理该文档的 `DOMImplementation` 对象。 |
| inputEncoding | 只读;返回解析该文档时所采用的字符编码(如 `UTF-8`;现代规范建议直接读取 `characterSet`)。 |
| lastChild | 只读;返回文档的最后一个子节点。 |
| nodeName | 只读;对于 `Document` 节点恒返回 `#document`。 |
| nodeType | 只读;对于 `Document` 节点恒返回 `9`(`Node.DOCUMENT_NODE`)。 |
| nodeValue | 对于 `Document` 节点恒返回 `null`(赋值无效)。 |
| strictErrorChecking | 历史 DOM Level 3 属性:设置或返回是否强制执行严格错误检查(现代 DOM 已移除)。 |
| xmlEncoding | 历史 DOM Level 3 属性:返回 XML 声明中标注的编码方式(如 `UTF-8`)。 |
| xmlStandalone | 历史 DOM Level 3 属性:返回或设置 XML 声明中的 `standalone` 标志。 |
| xmlVersion | 历史 DOM Level 3 属性:返回或设置 XML 声明中的版本号(如 `1.0`)。 |
Document 对象方法参考
| 方法 | 参数与功能说明 |
|---|---|
| adoptNode(sourceNode) | 将另一份文档中的节点直接过户至当前文档(原文档中会被移除),更新其 `ownerDocument` 并返回该节点。 |
| createAttribute(name) | 创建指定名称的 `Attr` 属性节点并返回。 |
| createAttributeNS(namespaceURI, qualifiedName) | 创建带命名空间 URI 与限定名的 `Attr` 属性节点并返回。 |
| createCDATASection(data) | 创建包含未转义文本的 `CDATASection` 节点并返回。 |
| createComment(data) | 创建包含指定注释文本的 `Comment` 节点并返回。 |
| createDocumentFragment() | 创建一个空的 `DocumentFragment` 轻量级容器并返回。 |
| createElement(tagName) | 创建指定标签名的 `Element` 元素节点并返回。 |
| createElementNS(namespaceURI, qualifiedName) | 创建带命名空间 URI 与限定名的 `Element` 元素节点并返回。 |
| createEntityReference(name) | 历史 DOM Core 方法:创建 `EntityReference` 实体引用节点(现代浏览器已移除)。 |
| createProcessingInstruction(target, data) | 创建指定目标与数据内容的 `ProcessingInstruction` 处理指令节点并返回。 |
| createTextNode(data) | 创建包含指定字符串的 `Text` 文本节点并返回。 |
| getElementById(elementId) | 返回拥有匹配 ID 类型属性的元素;XML 中该属性须经 DTD/Schema 或 `setIdAttribute*` 声明为 ID,未命中返回 `null`。 |
| getElementsByTagName(tagName) | 按文档顺序返回所有匹配指定标签名(`*` 匹配全部元素)的元素集合。 |
| getElementsByTagNameNS(namespaceURI, localName) | 返回同时匹配指定命名空间 URI 与本地名的所有后代元素集合。 |
| importNode(node, deep) | 从外部文档复制节点到当前文档:`deep=true` 递归复制整棵子树,`deep=false` 仅复制节点本身;原文档节点保持不变。 |
| normalizeDocument() | 历史 DOM Level 3 方法:依据 `domConfig` 对整份文档执行规范化(合并相邻文本、清除空文本节点并修正命名空间声明)。 |
| renameNode(node, namespaceURI, qualifiedName) | 历史 DOM Level 3 方法:修改已有元素或属性节点的命名空间与限定名(部分实现如 `minidom` 支持,现代浏览器已移除)。 |
离线验证 Document 元数据、全套节点工厂、命名空间/ID 查询及跨文档 importNode
"""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()
- 离线验证器通过全部 4 项用例:核验 Document 根节点属性与 XML 声明信息、9 类工厂节点的 ownerDocument、TagNameNS 与 getElementById 查询,以及跨文档 importNode 与 renameNode。
所需环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。
当前源码 SHA256:28eaafc1406d0622e1c2b48e1d85222872ae6a4dfa8b402162249ecf5bec4fb6
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。
ZIP SHA256:6e8cb11226b1e95c7d4cd12ff0735c71ae6e4d3d3987c6e87dab02d716253dfd
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`document.importNode(node, true)` 与 `document.adoptNode(node)` 在处理原文档节点时有何不同?
展开参考解答
`importNode()` 会创建原节点的副本(原节点仍留在原文档中完好无损);而 `adoptNode()` 直接把原节点从源文档中摘除并转移所有权给目标文档,不产生新副本。