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

验证节点树父子/同级/叶子不变量、首尾子节点及通用深度优先遍历

PYTHONWindows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。explore-nodetree.py
explore-nodetree.py154 行
"""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()
本例需在 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-nodetree-lab/explore-nodetree.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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