XML DOM 节点树
系统说明 XML DOM 节点树的层级结构,厘清根节点、父节点、子节点、叶子节点与同级节点的关系,并演示首尾子节点及缩进空白节点的影响。
学完这一章,你能够
- 系统说明 XML DOM 节点树的层级结构,厘清根节点、父节点、子节点、叶子节点与同级节点的关系,并演示首尾子节点及缩进空白节点的影响。
将 XML 文档抽象为节点树
XML DOM 将整份 XML 文档视为一棵彼此关联的节点树(Node Tree)。借助这棵树形结构,程序既可以定位并访问任意节点,也能够修改或删除节点内容,或者创建新元素并挂载到指定位置。整棵节点树以根元素为起点逐层向下分叉,最终在最低层级延伸至承载文字的文本节点——对应 `books.xml` 时,便形成了从 `<bookstore>` 到 `<book>`、子元素再到文本叶子的清晰层级。
父节点、子节点与同级节点关系
节点树中的每个节点都处在明确的层级关系之中,通常使用父节点(Parent)、子节点(Child)和同级节点(Sibling,即兄弟节点)来描述:位于树最顶端的节点称为根节点;除根节点之外的每一个节点都恰好拥有一个父节点;任意节点可以拥有零个、一个或多个子节点;没有任何子节点的末端节点称为叶子节点;拥有相同父节点的多个节点互为同级节点。
正因为 XML 数据天然按树形结构组织,程序即便事先并不了解文档的确切标签结构或数据类型,也可以通过父子与兄弟关系对整棵树执行通用的递归遍历;具体遍历编码技巧将在后续章节展开。
第一个子节点与最后一个子节点
观察单本图书的 XML 片段:`<book category="cooking">` 依次包含 `<title>`、`<author>`、`<year>` 和 `<price>` 四个子元素。从元素层级来看,`<title>` 是 `<book>` 的第一个子元素,`<price>` 是 `<book>` 的最后一个子元素,而 `<book>` 则是这四个元素的共同父节点。需要特别留意的是,在严格遵循 W3C DOM 规范的解析器中,标签之间若存在换行和缩进空格,它们也会生成空白文本节点并占据 `firstChild`/`lastChild` 位置,因此在现代浏览器 DOM 中常使用 `firstElementChild` / `lastElementChild` 或按 `nodeType === 1` 过滤。
验证节点树父子/同级/叶子不变量、首尾子节点及通用深度优先遍历
"""Offline XML DOM verification lab for Chapter 04 (nodetree)."""
import json
import sys
import xml.dom.minidom as minidom
from lxml import etree
VERSION = f"CPython {sys.version.split()[0]} + xml.dom.minidom + lxml {etree.__version__}"
SNIPPET_INDENTED = """<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>"""
SNIPPET_COMPACT = (
'<bookstore><book category="cooking">'
'<title lang="en">Everyday Italian</title>'
'<author>Giada De Laurentiis</author>'
'<year>2005</year>'
'<price>30.00</price>'
'</book></bookstore>'
)
def case_single_book_tree_first_last_child():
doc = minidom.parseString(SNIPPET_COMPACT)
book = doc.getElementsByTagName("book")[0]
child_parents = [c.parentNode.tagName for c in book.childNodes]
expected = {
"first_child": "title",
"last_child": "price",
"all_parents_are_book": True,
"sibling_count": 4,
}
actual = {
"first_child": book.firstChild.tagName,
"last_child": book.lastChild.tagName,
"all_parents_are_book": all(p == "book" for p in child_parents),
"sibling_count": len(book.childNodes),
}
return {
"name": "single_book_tree_first_last_child",
"summary": "验证紧凑 XML 片段中 title 为 book 的第一个子节点、price 为最后一个子节点,且四者共父节点 book",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_root_parent_leaf_sibling_invariants():
doc = minidom.parseString(SNIPPET_COMPACT)
root = doc.documentElement
book = root.firstChild
title = book.firstChild
leaf_text = title.firstChild
expected = {
"doc_parent_is_none": True,
"root_parent_is_doc": True,
"leaf_has_children": False,
"siblings_share_parent": True,
}
actual = {
"doc_parent_is_none": doc.parentNode is None,
"root_parent_is_doc": root.parentNode is doc,
"leaf_has_children": leaf_text.hasChildNodes(),
"siblings_share_parent": title.nextSibling.parentNode is title.parentNode,
}
return {
"name": "root_parent_leaf_sibling_invariants",
"summary": "校验节点树核心不变量:根节点位于顶端、叶子节点无子节点、同级节点拥有相同父节点",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_formatted_whitespace_vs_element_children():
doc = minidom.parseString(SNIPPET_INDENTED)
book = doc.getElementsByTagName("book")[0]
elem_children = [n.tagName for n in book.childNodes if n.nodeType == n.ELEMENT_NODE]
lxml_root = etree.fromstring(SNIPPET_INDENTED.encode("utf-8"))
lxml_children = [el.tag for el in lxml_root.find("book")]
expected = {
"indented_raw_child_count": 9,
"first_raw_child_is_whitespace_text": True,
"element_children": ["title", "author", "year", "price"],
"lxml_children_match": True,
}
actual = {
"indented_raw_child_count": len(book.childNodes),
"first_raw_child_is_whitespace_text": book.firstChild.nodeType == book.TEXT_NODE and not book.firstChild.nodeValue.strip(),
"element_children": elem_children,
"lxml_children_match": elem_children == lxml_children,
}
return {
"name": "formatted_whitespace_vs_element_children",
"summary": "对比缩进 XML 的空白文本子节点与纯元素子节点,并用 lxml.etree 核对元素序列",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_generic_depth_first_tree_traversal():
doc = minidom.parseString(SNIPPET_COMPACT)
visited = []
def walk(node):
if node.nodeType == node.ELEMENT_NODE:
visited.append(("E", node.tagName))
elif node.nodeType == node.TEXT_NODE and node.nodeValue.strip():
visited.append(("T", node.nodeValue.strip()))
for child in node.childNodes:
walk(child)
walk(doc.documentElement)
expected = [
("E", "bookstore"),
("E", "book"),
("E", "title"),
("T", "Everyday Italian"),
("E", "author"),
("T", "Giada De Laurentiis"),
("E", "year"),
("T", "2005"),
("E", "price"),
("T", "30.00"),
]
actual = visited
return {
"name": "generic_depth_first_tree_traversal",
"summary": "不预设具体标签名对节点树执行通用深度优先遍历,收集全部元素节点与叶子文本",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_single_book_tree_first_last_child(),
case_root_parent_leaf_sibling_invariants(),
case_formatted_whitespace_vs_element_children(),
case_generic_depth_first_tree_traversal(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 确认紧凑 XML 下 book 首尾子节点分别为 title 与 price、缩进 XML 产生空白文本子节点、所有节点树关系不变量及通用 DFS 遍历全部通过。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
当前源码 SHA256:e109b9becb0ea462781b1654262a7ff4bb01b452569b6df64e0d4349b46e2ad0
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
ZIP SHA256:103a33ee8a83cdc33e5bf8f6757b361ff20db05e9617f5600b49a1ac565506bf
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在包含换行和缩进空格的 XML 中,直接访问 `<book>` 的 `firstChild` 为什么有时得到的不是 `<title>`?
展开参考解答
因为 W3C DOM 会把 `<book>` 开始标签与 `<title>` 之间的换行符和缩进空格解析为一个空白文本节点(`nodeType === 3`),它排在 `<title>` 之前成为第一个子节点。