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

实测 parentNode 向上导航与跳过空白文本节点的首尾/兄弟元素安全导航

PYTHONWindows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。explore-nodes-navigate.py
explore-nodes-navigate.py164 行
"""Offline XML DOM verification lab for Chapter 13 (nodes-navigate)."""
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__}"

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 get_first_element_child(node):
    y = node.firstChild
    while y is not None and y.nodeType != 1:
        y = y.nextSibling
    return y


def get_last_element_child(node):
    y = node.lastChild
    while y is not None and y.nodeType != 1:
        y = y.previousSibling
    return y


def get_next_element_sibling(node):
    y = node.nextSibling
    while y is not None and y.nodeType != 1:
        y = y.nextSibling
    return y


def get_prev_element_sibling(node):
    y = node.previousSibling
    while y is not None and y.nodeType != 1:
        y = y.previousSibling
    return y


def case_navigate_parent_node():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    title0 = doc.getElementsByTagName("title")[0]
    expected = {
        "book_parent_name": "bookstore",
        "title_parent_name": "book",
        "root_parent_name": "#document",
    }
    actual = {
        "book_parent_name": book0.parentNode.nodeName,
        "title_parent_name": title0.parentNode.nodeName,
        "root_parent_name": doc.documentElement.parentNode.nodeName,
    }
    return {
        "name": "navigate_parent_node",
        "summary": "通过 parentNode 属性从 book、title 与根元素逐级向上导航并核对父节点名",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_safe_element_first_and_last_child():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    first_el = get_first_element_child(book0)
    last_el = get_last_element_child(book0)
    expected = {
        "raw_first_child_type": 3,
        "safe_first_element": "title",
        "safe_last_element": "price",
    }
    actual = {
        "raw_first_child_type": book0.firstChild.nodeType,
        "safe_first_element": first_el.nodeName,
        "safe_last_element": last_el.nodeName,
    }
    return {
        "name": "safe_element_first_and_last_child",
        "summary": "使用跳过非元素节点的辅助函数获取第一个子元素(title)与最后一个子元素(price)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_safe_element_next_and_prev_sibling():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    forward = []
    cur = get_first_element_child(book0)
    while cur is not None:
        forward.append(cur.nodeName)
        cur = get_next_element_sibling(cur)
    backward = []
    cur = get_last_element_child(book0)
    while cur is not None:
        backward.append(cur.nodeName)
        cur = get_prev_element_sibling(cur)
    expected = {
        "forward": ["title", "author", "year", "price"],
        "backward": ["price", "year", "author", "title"],
    }
    actual = {"forward": forward, "backward": backward}
    return {
        "name": "safe_element_next_and_prev_sibling",
        "summary": "验证带空值保护的 nextSibling/previousSibling 元素导航函数在正反向遍历及边界终止处均安全返回",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lxml_cross_verify_navigation():
    root = etree.fromstring(BOOKS_XML.encode("utf-8"))
    book0 = root.find("book")
    title0 = book0[0]
    price0 = book0[-1]
    expected = {
        "parent": "bookstore",
        "first_next": "author",
        "last_prev": "year",
    }
    actual = {
        "parent": book0.getparent().tag,
        "first_next": title0.getnext().tag,
        "last_prev": price0.getprevious().tag,
    }
    return {
        "name": "lxml_cross_verify_navigation",
        "summary": "使用 lxml.etree 的 getparent/getnext/getprevious 交叉校验元素导航关系",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_navigate_parent_node(),
        case_safe_element_first_and_last_child(),
        case_safe_element_next_and_prev_sibling(),
        case_lxml_cross_verify_navigation(),
    ]
    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-navigate-lab/explore-nodes-navigate.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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