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

解析完整 books.xml 并验证五类 DOM 节点与文本节点归属规则

PYTHONWindows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。explore-nodes.py
explore-nodes.py162 行
"""Offline XML DOM verification lab for Chapter 03 (nodes)."""
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_five_core_node_kinds():
    sample = '<?xml version="1.0" encoding="UTF-8"?><bookstore><!-- catalog --><book category="cooking"><year>2005</year></book></bookstore>'
    doc = minidom.parseString(sample)
    comment = doc.documentElement.childNodes[0]
    book = doc.documentElement.childNodes[1]
    attr = book.getAttributeNode("category")
    text = book.firstChild.firstChild
    expected = {
        "document_type": 9,
        "element_type": 1,
        "text_type": 3,
        "attribute_type": 2,
        "comment_type": 8,
        "comment_data": " catalog ",
    }
    actual = {
        "document_type": doc.nodeType,
        "element_type": book.nodeType,
        "text_type": text.nodeType,
        "attribute_type": attr.nodeType,
        "comment_type": comment.nodeType,
        "comment_data": comment.nodeValue,
    }
    return {
        "name": "five_core_node_kinds",
        "summary": "验证 XML 文档中文档、元素、文本、属性、注释五类核心 DOM 节点的 nodeType",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_books_xml_structure_inspection():
    doc = minidom.parseString(BOOKS_XML)
    books = doc.getElementsByTagName("book")
    third_authors = [a.firstChild.nodeValue for a in books[2].getElementsByTagName("author")]
    lxml_root = etree.fromstring(BOOKS_XML.encode("utf-8"))
    expected = {
        "root_name": "bookstore",
        "book_count": 4,
        "third_book_author_count": 5,
        "fourth_book_cover": "paperback",
        "lxml_book_count": 4,
    }
    actual = {
        "root_name": doc.documentElement.tagName,
        "book_count": len(books),
        "third_book_author_count": len(third_authors),
        "fourth_book_cover": books[3].getAttribute("cover"),
        "lxml_book_count": len(lxml_root.findall("book")),
    }
    return {
        "name": "books_xml_structure_inspection",
        "summary": "解析完整 books.xml,核对根元素 bookstore、4 本书、第 3 本书 5 位作者与第 4 本书 cover 属性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_first_book_children_and_text_nodes():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    elems = [n for n in book0.childNodes if n.nodeType == n.ELEMENT_NODE]
    pairs = [(e.tagName, e.firstChild.nodeValue) for e in elems]
    expected = [
        ("title", "Everyday Italian"),
        ("author", "Giada De Laurentiis"),
        ("year", "2005"),
        ("price", "30.00"),
    ]
    actual = pairs
    return {
        "name": "first_book_children_and_text_nodes",
        "summary": "核对第一个 book 节点的 4 个子元素及其对应文本节点内容",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_text_stored_in_text_node_not_element():
    doc = minidom.parseString(BOOKS_XML)
    year_elem = doc.getElementsByTagName("year")[0]
    year_text = year_elem.firstChild
    expected = {
        "element_node_name": "year",
        "element_node_value_is_none": True,
        "child_node_name": "#text",
        "child_node_type": 3,
        "child_node_value": "2005",
    }
    actual = {
        "element_node_name": year_elem.nodeName,
        "element_node_value_is_none": year_elem.nodeValue is None,
        "child_node_name": year_text.nodeName,
        "child_node_type": year_text.nodeType,
        "child_node_value": year_text.nodeValue,
    }
    return {
        "name": "text_stored_in_text_node_not_element",
        "summary": "验证 <year>2005</year> 中元素节点的 nodeValue 为空,文本 '2005' 实际存放在子文本节点中",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_five_core_node_kinds(),
        case_books_xml_structure_inspection(),
        case_first_book_children_and_text_nodes(),
        case_text_stored_in_text_node_not_element(),
    ]
    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-lab/explore-nodes.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-nodes.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章) · 含当前章节或实例 · mbskycom202612a2770.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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