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

使用 xml.dom.minidom 与 lxml 离线解析 books.xml 验证节点树层级关系

PYTHONWindows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。explore-tutorial.py
explore-tutorial.py162 行
"""Offline XML DOM verification lab for Chapter 01 (tutorial)."""
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>
    <book category="web">
        <title lang="en">XQuery Kick Start</title>
        <author>James McGovern</author>
        <author>Per Bothner</author>
        <author>Kurt Cagle</author>
        <author>James Linn</author>
        <author>Vaidyanathan Nagarajan</author>
        <year>2003</year>
        <price>49.99</price>
    </book>
    <book category="web" cover="paperback">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>"""


def case_parse_bookstore_tree_structure():
    doc = minidom.parseString(BOOKS_XML)
    root = doc.documentElement
    books = doc.getElementsByTagName("book")
    first_children = [n for n in books[0].childNodes if n.nodeType == n.ELEMENT_NODE]
    leaf_texts = {n.tagName: n.firstChild.nodeValue for n in first_children}
    expected = {
        "root_tag": "bookstore",
        "book_count": 4,
        "first_book_tags": ["title", "author", "year", "price"],
        "leaf_texts": {
            "title": "Everyday Italian",
            "author": "Giada De Laurentiis",
            "year": "2005",
            "price": "30.00",
        },
    }
    actual = {
        "root_tag": root.tagName,
        "book_count": len(books),
        "first_book_tags": [n.tagName for n in first_children],
        "leaf_texts": leaf_texts,
    }
    return {
        "name": "parse_bookstore_tree_structure",
        "summary": "使用 xml.dom.minidom 将 books.xml 解析为节点树,验证根节点、book 数量与叶子文本节点",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nodetree_hierarchy_relationships():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    title0 = book0.getElementsByTagName("title")[0]
    next_elem = title0.nextSibling
    while next_elem is not None and next_elem.nodeType != next_elem.ELEMENT_NODE:
        next_elem = next_elem.nextSibling
    expected = {
        "book_parent": "bookstore",
        "book_category": "cooking",
        "title_lang": "en",
        "title_next_element_sibling": "author",
    }
    actual = {
        "book_parent": book0.parentNode.tagName,
        "book_category": book0.getAttribute("category"),
        "title_lang": title0.getAttribute("lang"),
        "title_next_element_sibling": next_elem.tagName if next_elem else None,
    }
    return {
        "name": "nodetree_hierarchy_relationships",
        "summary": "核对节点树示意图中的父子、属性(category/lang)与兄弟节点(title/author)层级关系",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cross_check_with_lxml_etree():
    root = etree.fromstring(BOOKS_XML.encode("utf-8"))
    titles = [el.text for el in root.findall(".//title")]
    categories = [el.get("category") for el in root.findall("book")]
    expected = {
        "root_tag": "bookstore",
        "titles": ["Everyday Italian", "Harry Potter", "XQuery Kick Start", "Learning XML"],
        "categories": ["cooking", "children", "web", "web"],
    }
    actual = {
        "root_tag": root.tag,
        "titles": titles,
        "categories": categories,
    }
    return {
        "name": "cross_check_with_lxml_etree",
        "summary": "使用 lxml.etree 交叉解析 books.xml,确认根标签、书名列表与分类属性和 DOM 树一致",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_dom_official_specs_catalog():
    refs = [
        ("WHATWG DOM Living Standard", "https://dom.spec.whatwg.org/"),
        ("W3C DOM Level 3 Core", "https://www.w3.org/TR/DOM-Level-3-Core/"),
        ("MDN XML DOM 指南", "https://developer.mozilla.org/en-US/docs/Web/XML/Guides/Parsing_and_serializing_XML"),
    ]
    expected = {
        "count": 3,
        "all_https": True,
        "hosts": ["dom.spec.whatwg.org", "www.w3.org", "developer.mozilla.org"],
    }
    actual = {
        "count": len(refs),
        "all_https": all(u.startswith("https://") for _, u in refs),
        "hosts": [u.split("/")[2] for _, u in refs],
    }
    return {
        "name": "dom_official_specs_catalog",
        "summary": "校验 W3C/WHATWG 与 MDN XML DOM 权威技术参考入口清单",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_parse_bookstore_tree_structure(),
        case_nodetree_hierarchy_relationships(),
        case_cross_check_with_lxml_etree(),
        case_dom_official_specs_catalog(),
    ]
    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-tutorial-lab/explore-tutorial.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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