DOM 节点类型
完整梳理 W3C XML DOM 定义的 12 种节点类型、允许的子节点层次关系、各节点类型对应的 nodeName 与 nodeValue 返回值规律,以及 1–12 命名常量对照表。
学完这一章,你能够
- 完整梳理 W3C XML DOM 定义的 12 种节点类型、允许的子节点层次关系、各节点类型对应的 nodeName 与 nodeValue 返回值规律,以及 1–12 命名常量对照表。
DOM 节点层次与书目演练
XML DOM 将整份 XML 文档抽象为一套层次化的节点对象树,文档中的元素、属性、文本、注释、CDATA 区段、处理指令与文档类型声明均对应明确的节点类型。
学习节点类型时,常见入门演练是加载标准书目样本 `books.xml`(例如借助外部加载函数 `loadXMLDoc()` 解析文档),分别遍历各节点输出其 `nodeName` 与 `nodeType`,再对比元素自身 `nodeValue`(恒为 `null`)与其子文本节点 `nodeValue` 的差异。
W3C 12 种节点类型与允许的子节点
W3C DOM Core 规范定义了 12 种节点接口,并严格规定了每种节点允许挂载的子节点类型。容器型节点(如 `Document`、`DocumentFragment`、`Element`)可包含多种子节点,其中 `Document` 最多只能有一个根 `Element`;而叶子节点(如 `Text`、`CDATASection`、`Comment`、`ProcessingInstruction`、`DocumentType`、`Notation`)不允许拥有任何子节点,强行调用 `appendChild()` 会抛出 `HierarchyRequestError`。
各节点类型的 nodeName、nodeValue 与命名常量
不同类型的节点在读取 `nodeName` 与 `nodeValue` 时表现截然不同:元素节点与文档节点的 `nodeValue` 恒为 `null`,而 `Attr`、`Text`、`CDATASection`、`Comment` 与 `ProcessingInstruction` 则通过 `nodeValue` 暴露具体内容;同时 `DocumentFragment` 的标准 `nodeName` 为 `#document-fragment`(旧式资料常写作 `#document fragment`)。判断节点类别时,既可比较 `nodeType` 数值(1–12),也可使用语义更清晰的 `Node` 命名常量(如 `Node.ELEMENT_NODE`、`Node.TEXT_NODE`);需补充说明的是,现代 DOM Living Standard 已将 `EntityReference`、`Entity` 与 `Notation` 标记为历史遗留类型。
W3C XML DOM 12 种节点类型与允许子节点对照
| 节点类型 | 说明 | 允许的子节点类型 |
| Document | 代表整个 XML 文档,是 DOM 树的顶层根节点。 | Element(最多 1 个)、ProcessingInstruction、Comment、DocumentType |
| DocumentFragment | 轻量级文档片段容器,用于暂存和批量插入局部节点树。 | Element、ProcessingInstruction、Comment、Text、CDATASection、EntityReference |
| DocumentType | 提供访问文档关联 DTD(文档类型声明)与实体/符号声明的接口。 | None(无子节点) |
| ProcessingInstruction | 代表向特定处理器传递指令的处理指令节点(<?target data?>)。 | None(无子节点) |
| EntityReference | 代表 XML 中的实体引用节点(现代浏览器通常已自动展开实体)。 | Element、ProcessingInstruction、Comment、Text、CDATASection、EntityReference |
| Element | 代表 XML 文档中的一个标签元素。 | Element、Text、Comment、ProcessingInstruction、CDATASection、EntityReference |
| Attr | 代表附属在元素上的属性节点(不属于元素的 childNodes)。 | Text、EntityReference(在 DOM 1/2 规范中定义) |
| Text | 代表元素或属性中的纯文本字符内容。 | None(无子节点) |
| CDATASection | 代表 <![CDATA[...]]> 区段,内部字符不会被解析器当作标记或实体展开。 | None(无子节点) |
| Comment | 代表 XML 文档中的注释节点(<!--...-->)。 | None(无子节点) |
| Entity | 代表 DTD 中声明的已解析或未解析实体(历史 DOM Core 节点)。 | Element、ProcessingInstruction、Comment、Text、CDATASection、EntityReference |
| Notation | 代表 DTD 中声明的符号(NOTATION,历史 DOM Core 节点)。 | None(无子节点) |
各节点类型的 nodeName 与 nodeValue 返回值
| 节点类型 | nodeName 返回值 | nodeValue 返回值 |
| Document | #document | null |
| DocumentFragment | #document-fragment | null |
| DocumentType | 文档类型名称(如 bookstore) | null |
| EntityReference | 实体引用名称 | null |
| Element | 元素标签名(tagName) | null |
| Attr | 属性名称 | 属性值字符串 |
| ProcessingInstruction | 处理指令目标(target) | 处理指令正文内容(data) |
| Comment | #comment | 注释正文文本 |
| Text | #text | 文本节点字符内容 |
| CDATASection | #cdata-section | CDATA 区段正文内容 |
| Entity | 实体名称 | null |
| Notation | 符号名称 | null |
DOM 节点类型数值与命名常量对照
| nodeType 数值 | Node 命名常量 |
| 1 | ELEMENT_NODE |
| 2 | ATTRIBUTE_NODE |
| 3 | TEXT_NODE |
| 4 | CDATA_SECTION_NODE |
| 5 | ENTITY_REFERENCE_NODE |
| 6 | ENTITY_NODE |
| 7 | PROCESSING_INSTRUCTION_NODE |
| 8 | COMMENT_NODE |
| 9 | DOCUMENT_NODE |
| 10 | DOCUMENT_TYPE_NODE |
| 11 | DOCUMENT_FRAGMENT_NODE |
| 12 | NOTATION_NODE |
离线实测 12 个节点类型常量、nodeName/nodeValue 矩阵与叶子节点层级约束
展开查看收起
"""Offline XML DOM verification lab for Chapter 22 (nodetype)."""
import json
from xml.dom import Node, minidom
VERSION = "CPython 3.12.14 offline XML DOM verifier (xml.dom.Node + xml.dom.minidom)"
BOOKS_XML = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
</book>
</bookstore>
"""
def case_nodetype_constants_1_to_12():
constants = {
1: Node.ELEMENT_NODE,
2: Node.ATTRIBUTE_NODE,
3: Node.TEXT_NODE,
4: Node.CDATA_SECTION_NODE,
5: Node.ENTITY_REFERENCE_NODE,
6: Node.ENTITY_NODE,
7: Node.PROCESSING_INSTRUCTION_NODE,
8: Node.COMMENT_NODE,
9: Node.DOCUMENT_NODE,
10: Node.DOCUMENT_TYPE_NODE,
11: Node.DOCUMENT_FRAGMENT_NODE,
12: Node.NOTATION_NODE,
}
expected = {str(k): k for k in range(1, 13)}
actual = {str(k): v for k, v in constants.items()}
return {
"name": "nodetype_constants_1_to_12",
"summary": "验证 W3C DOM 1–12 全部节点类型命名常量与数值映射",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_node_name_and_value_matrix():
impl = minidom.getDOMImplementation()
dt = impl.createDocumentType("bookstore", "", "books.dtd")
doc = impl.createDocument(None, "bookstore", dt)
elem = doc.documentElement
elem.setAttribute("category", "xml")
attr = elem.getAttributeNode("category")
frag = doc.createDocumentFragment()
txt = doc.createTextNode("DOM Core")
cdata = doc.createCDATASection("<raw>&data</raw>")
comment = doc.createComment("sample comment")
pi = doc.createProcessingInstruction("xml-stylesheet", 'type="text/xsl" href="style.xsl"')
expected = {
"Document": [9, "#document", None],
"DocumentFragment": [11, "#document-fragment", None],
"DocumentType": [10, "bookstore", None],
"Element": [1, "bookstore", None],
"Attr": [2, "category", "xml"],
"Text": [3, "#text", "DOM Core"],
"CDATASection": [4, "#cdata-section", "<raw>&data</raw>"],
"Comment": [8, "#comment", "sample comment"],
"ProcessingInstruction": [7, "xml-stylesheet", 'type="text/xsl" href="style.xsl"'],
}
actual = {
"Document": [doc.nodeType, doc.nodeName, doc.nodeValue],
"DocumentFragment": [frag.nodeType, frag.nodeName, frag.nodeValue],
"DocumentType": [dt.nodeType, dt.nodeName, dt.nodeValue],
"Element": [elem.nodeType, elem.nodeName, elem.nodeValue],
"Attr": [attr.nodeType, attr.nodeName, attr.nodeValue],
"Text": [txt.nodeType, txt.nodeName, txt.nodeValue],
"CDATASection": [cdata.nodeType, cdata.nodeName, cdata.nodeValue],
"Comment": [comment.nodeType, comment.nodeName, comment.nodeValue],
"ProcessingInstruction": [pi.nodeType, pi.nodeName, pi.nodeValue],
}
return {
"name": "node_name_and_value_matrix",
"summary": "真实实例化各类 DOM 节点并核验 nodeType、nodeName 与 nodeValue 返回值规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_node_hierarchy_allowed_children():
doc = minidom.parseString("<root/>")
leaf_nodes = [
("Text", doc.createTextNode("leaf")),
("CDATASection", doc.createCDATASection("raw")),
("Comment", doc.createComment("note")),
("ProcessingInstruction", doc.createProcessingInstruction("pi", "v=1")),
]
rejected = []
for label, node in leaf_nodes:
try:
node.appendChild(doc.createElement("bad"))
except Exception as exc:
rejected.append((label, type(exc).__name__))
frag = doc.createDocumentFragment()
frag.appendChild(doc.createElement("a"))
frag.appendChild(doc.createTextNode("t"))
frag.appendChild(doc.createComment("c"))
frag.appendChild(doc.createCDATASection("cd"))
frag.appendChild(doc.createProcessingInstruction("p", "d"))
expected = {
"leaf_rejections": [
["Text", "HierarchyRequestErr"],
["CDATASection", "HierarchyRequestErr"],
["Comment", "HierarchyRequestErr"],
["ProcessingInstruction", "HierarchyRequestErr"],
],
"fragment_child_types": [1, 3, 8, 4, 7],
}
actual = {
"leaf_rejections": [[k, v] for k, v in rejected],
"fragment_child_types": [n.nodeType for n in frag.childNodes],
}
return {
"name": "node_hierarchy_allowed_children",
"summary": "验证叶子节点拒绝添加子节点(HierarchyRequestErr)与 DocumentFragment 允许的子节点类型",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_books_xml_nodename_nodetype_nodevalue():
doc = minidom.parseString(BOOKS_XML)
first_book = doc.getElementsByTagName("book")[0]
elem_summary = [
[n.nodeName, n.nodeType, n.nodeValue, n.firstChild.nodeValue]
for n in first_book.childNodes
if n.nodeType == Node.ELEMENT_NODE
]
expected = [
["title", 1, None, "Everyday Italian"],
["author", 1, None, "Giada De Laurentiis"],
["year", 1, None, "2005"],
]
actual = elem_summary
return {
"name": "books_xml_nodename_nodetype_nodevalue",
"summary": "解析 books.xml 遍历元素节点,对比元素自身的 nodeValue(None) 与其子文本节点的文本值",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_nodetype_constants_1_to_12(),
case_node_name_and_value_matrix(),
case_node_hierarchy_allowed_children(),
case_books_xml_nodename_nodetype_nodevalue(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为在 W3C DOM 规范中,元素节点(`nodeType === 1`)的 `nodeValue` 恒为 `null`,标签内部的文字实际保存在该元素下属的子文本节点(`nodeType === 3`)中,需要访问 `element.firstChild.nodeValue` 或 `element.textContent`。