蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测紧凑与缩进 XML 的子节点遍历及多层级递归遍历

PYTHONWindows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。explore-nodes-traverse.py
explore-nodes-traverse.py144 行
"""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()
本例需在 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/dom-nodes-traverse-lab/explore-nodes-traverse.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-nodes-traverse.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:XML DOM

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2782.zip

下载课程关联工程包:XML DOM

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习