蓝色天空网mbsky.com · 知识 · 实践 · 创造XML DOM · 本地阅读预览
教程 / XML / Web Service / XML DOM

XML DOM 遍历节点树

讲解节点树遍历(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 的子节点遍历及多层级递归遍历

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 确认紧凑 XML 输出与示例逐行一致,带缩进 XML 通过 nodeType==1 过滤空白文本节点避免越界,完整多层级递归遍历与 lxml.etree 一致。
实测紧凑与缩进 XML 的子节点遍历及多层级递归遍历

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

当前源码 SHA256:6131510d36bd9b7fc1edac066841fcb7fce35cedac008f0429e0b7f63395936c

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载XML DOM 遍历节点树实验

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

ZIP SHA256:b9fecdae4f6b27521dcb739f9e218ad85a243baae3b48912ba3f0d8691645d95

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

如果把本章示例中的紧凑 XML 字符串改写成带换行缩进的多行 XML,直接执行 `x[i].childNodes[0].nodeValue` 会发生什么问题?

展开参考解答

带换行的 XML 会在元素间生成空白文本节点;文本节点本身没有子节点(`childNodes` 为空),访问其 `childNodes[0].nodeValue` 会抛出空引用或越界异常,因此应先过滤 `nodeType === 1`。

规范与官方依据