XML DOM 遍历节点树
讲解节点树遍历(Traverse)的概念,演示使用 DOMParser 解析 XML 字符串并循环 documentElement.childNodes 提取子元素名称与文本值,并提示带缩进 XML 需过滤空白文本节点。
学完这一章,你能够
- 讲解节点树遍历(Traverse)的概念,演示使用 DOMParser 解析 XML 字符串并循环 documentElement.childNodes 提取子元素名称与文本值,并提示带缩进 XML 需过滤空白文本节点。
遍历节点树的概念与应用场景
在 DOM 编程中,“遍历(Traverse)”指的是沿着节点树逐个循环或移动访问节点的动作。当业务需要一次性提取整份 XML 文档中每个子元素的标签名与文本内容,或者批量检查、统计节点数据时,就需要通过遍历节点树来实现。下面以单本 `<book>` 元素为例,展示如何循环读取其全部子节点的名称和值。
循环 documentElement.childNodes 提取节点名与值
完整示例首先把紧凑拼接的 `<book><title>Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year></book>` 字符串交给 `new DOMParser().parseFromString(text, "text/xml")` 载入 `xmlDoc`,接着通过 `xmlDoc.documentElement.childNodes` 取得根元素的子节点列表,并在 `for` 循环中依次拼接 `x[i].nodeName + ": " + x[i].childNodes[0].nodeValue`,最终输出 `title: Everyday Italian`、`author: Giada De Laurentiis` 与 `year: 2005` 三行结果。需要注意的是,该例之所以无需跳过空白文本节点,是因为 XML 字符串标签之间没有换行和空格;若 XML 包含缩进格式化,务必先判断 `nodeType === 1`(或改用 `children`)再读取 `childNodes[0]`。
实测紧凑与缩进 XML 的子节点遍历及多层级递归遍历
展开查看收起
"""Offline XML DOM verification lab for Chapter 11 (nodes-traverse)."""
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__}"
COMPACT_BOOK = (
"<book>"
"<title>Everyday Italian</title>"
"<author>Giada De Laurentiis</author>"
"<year>2005</year>"
"</book>"
)
INDENTED_BOOK = """<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
</book>"""
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>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>"""
def case_traverse_compact_book_children():
doc = minidom.parseString(COMPACT_BOOK)
x = doc.documentElement.childNodes
lines = [f"{node.nodeName}: {node.childNodes[0].nodeValue}" for node in x]
expected = {
"child_count": 3,
"lines": [
"title: Everyday Italian",
"author: Giada De Laurentiis",
"year: 2005",
],
}
actual = {
"child_count": len(x),
"lines": lines,
}
return {
"name": "traverse_compact_book_children",
"summary": "解析无空白缩进的 book XML 字符串并循环 documentElement.childNodes 输出每项名称与文本值",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_traverse_indented_book_with_filter():
doc = minidom.parseString(INDENTED_BOOK)
raw_nodes = doc.documentElement.childNodes
filtered = [
f"{node.nodeName}: {node.childNodes[0].nodeValue}"
for node in raw_nodes
if node.nodeType == node.ELEMENT_NODE
]
expected = {
"raw_child_count": 7,
"whitespace_text_count": 4,
"filtered_lines": [
"title: Everyday Italian",
"author: Giada De Laurentiis",
"year: 2005",
],
}
actual = {
"raw_child_count": len(raw_nodes),
"whitespace_text_count": sum(1 for n in raw_nodes if n.nodeType == n.TEXT_NODE),
"filtered_lines": filtered,
}
return {
"name": "traverse_indented_book_with_filter",
"summary": "演示带缩进 XML 必须按 nodeType==1 过滤空白文本节点,避免直接访问 childNodes[0] 触发越界",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_recursive_full_document_traversal():
doc = minidom.parseString(BOOKS_XML)
leaf_entries = []
def traverse(node, depth=0):
if node.nodeType == node.ELEMENT_NODE:
elem_kids = [c for c in node.childNodes if c.nodeType == node.ELEMENT_NODE]
if not elem_kids and node.firstChild and node.firstChild.nodeType == node.TEXT_NODE:
leaf_entries.append((depth, node.tagName, node.firstChild.nodeValue))
else:
for c in elem_kids:
traverse(c, depth + 1)
traverse(doc.documentElement)
lxml_root = etree.fromstring(BOOKS_XML.encode("utf-8"))
lxml_leaves = [el.tag for el in lxml_root.iter() if len(el) == 0]
expected = {
"leaf_count": 8,
"first_leaf": (2, "title", "Everyday Italian"),
"last_leaf": (2, "price", "29.99"),
"matches_lxml_leaf_tags": True,
}
actual = {
"leaf_count": len(leaf_entries),
"first_leaf": leaf_entries[0],
"last_leaf": leaf_entries[-1],
"matches_lxml_leaf_tags": [tag for _, tag, _ in leaf_entries] == lxml_leaves,
}
return {
"name": "recursive_full_document_traversal",
"summary": "递归遍历完整多层级 books.xml 提取全部叶子元素及深度,并与 lxml.etree 交叉核对",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_traverse_compact_book_children(),
case_traverse_indented_book_with_filter(),
case_recursive_full_document_traversal(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
带换行的 XML 会在元素间生成空白文本节点;文本节点本身没有子节点(`childNodes` 为空),访问其 `childNodes[0].nodeValue` 会抛出空引用或越界异常,因此应先过滤 `nodeType === 1`。