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

离线实测 12 个节点类型常量、nodeName/nodeValue 矩阵与叶子节点层级约束

PYTHONWindows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。explore-nodetype.py
explore-nodetype.py172 行
"""Offline XML DOM verification lab for Chapter 22 (nodetype)."""
import json
from xml.dom import Node, minidom

VERSION = "CPython 3.12.14 offline XML DOM verifier (xml.dom.Node + xml.dom.minidom)"

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>
  </book>
  <book category="web">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
  </book>
</bookstore>
"""


def case_nodetype_constants_1_to_12():
    constants = {
        1: Node.ELEMENT_NODE,
        2: Node.ATTRIBUTE_NODE,
        3: Node.TEXT_NODE,
        4: Node.CDATA_SECTION_NODE,
        5: Node.ENTITY_REFERENCE_NODE,
        6: Node.ENTITY_NODE,
        7: Node.PROCESSING_INSTRUCTION_NODE,
        8: Node.COMMENT_NODE,
        9: Node.DOCUMENT_NODE,
        10: Node.DOCUMENT_TYPE_NODE,
        11: Node.DOCUMENT_FRAGMENT_NODE,
        12: Node.NOTATION_NODE,
    }
    expected = {str(k): k for k in range(1, 13)}
    actual = {str(k): v for k, v in constants.items()}
    return {
        "name": "nodetype_constants_1_to_12",
        "summary": "验证 W3C DOM 1–12 全部节点类型命名常量与数值映射",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_node_name_and_value_matrix():
    impl = minidom.getDOMImplementation()
    dt = impl.createDocumentType("bookstore", "", "books.dtd")
    doc = impl.createDocument(None, "bookstore", dt)
    elem = doc.documentElement
    elem.setAttribute("category", "xml")
    attr = elem.getAttributeNode("category")
    frag = doc.createDocumentFragment()
    txt = doc.createTextNode("DOM Core")
    cdata = doc.createCDATASection("<raw>&data</raw>")
    comment = doc.createComment("sample comment")
    pi = doc.createProcessingInstruction("xml-stylesheet", 'type="text/xsl" href="style.xsl"')

    expected = {
        "Document": [9, "#document", None],
        "DocumentFragment": [11, "#document-fragment", None],
        "DocumentType": [10, "bookstore", None],
        "Element": [1, "bookstore", None],
        "Attr": [2, "category", "xml"],
        "Text": [3, "#text", "DOM Core"],
        "CDATASection": [4, "#cdata-section", "<raw>&data</raw>"],
        "Comment": [8, "#comment", "sample comment"],
        "ProcessingInstruction": [7, "xml-stylesheet", 'type="text/xsl" href="style.xsl"'],
    }
    actual = {
        "Document": [doc.nodeType, doc.nodeName, doc.nodeValue],
        "DocumentFragment": [frag.nodeType, frag.nodeName, frag.nodeValue],
        "DocumentType": [dt.nodeType, dt.nodeName, dt.nodeValue],
        "Element": [elem.nodeType, elem.nodeName, elem.nodeValue],
        "Attr": [attr.nodeType, attr.nodeName, attr.nodeValue],
        "Text": [txt.nodeType, txt.nodeName, txt.nodeValue],
        "CDATASection": [cdata.nodeType, cdata.nodeName, cdata.nodeValue],
        "Comment": [comment.nodeType, comment.nodeName, comment.nodeValue],
        "ProcessingInstruction": [pi.nodeType, pi.nodeName, pi.nodeValue],
    }
    return {
        "name": "node_name_and_value_matrix",
        "summary": "真实实例化各类 DOM 节点并核验 nodeType、nodeName 与 nodeValue 返回值规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_node_hierarchy_allowed_children():
    doc = minidom.parseString("<root/>")
    leaf_nodes = [
        ("Text", doc.createTextNode("leaf")),
        ("CDATASection", doc.createCDATASection("raw")),
        ("Comment", doc.createComment("note")),
        ("ProcessingInstruction", doc.createProcessingInstruction("pi", "v=1")),
    ]
    rejected = []
    for label, node in leaf_nodes:
        try:
            node.appendChild(doc.createElement("bad"))
        except Exception as exc:
            rejected.append((label, type(exc).__name__))

    frag = doc.createDocumentFragment()
    frag.appendChild(doc.createElement("a"))
    frag.appendChild(doc.createTextNode("t"))
    frag.appendChild(doc.createComment("c"))
    frag.appendChild(doc.createCDATASection("cd"))
    frag.appendChild(doc.createProcessingInstruction("p", "d"))

    expected = {
        "leaf_rejections": [
            ["Text", "HierarchyRequestErr"],
            ["CDATASection", "HierarchyRequestErr"],
            ["Comment", "HierarchyRequestErr"],
            ["ProcessingInstruction", "HierarchyRequestErr"],
        ],
        "fragment_child_types": [1, 3, 8, 4, 7],
    }
    actual = {
        "leaf_rejections": [[k, v] for k, v in rejected],
        "fragment_child_types": [n.nodeType for n in frag.childNodes],
    }
    return {
        "name": "node_hierarchy_allowed_children",
        "summary": "验证叶子节点拒绝添加子节点(HierarchyRequestErr)与 DocumentFragment 允许的子节点类型",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_books_xml_nodename_nodetype_nodevalue():
    doc = minidom.parseString(BOOKS_XML)
    first_book = doc.getElementsByTagName("book")[0]
    elem_summary = [
        [n.nodeName, n.nodeType, n.nodeValue, n.firstChild.nodeValue]
        for n in first_book.childNodes
        if n.nodeType == Node.ELEMENT_NODE
    ]
    expected = [
        ["title", 1, None, "Everyday Italian"],
        ["author", 1, None, "Giada De Laurentiis"],
        ["year", 1, None, "2005"],
    ]
    actual = elem_summary
    return {
        "name": "books_xml_nodename_nodetype_nodevalue",
        "summary": "解析 books.xml 遍历元素节点,对比元素自身的 nodeValue(None) 与其子文本节点的文本值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_nodetype_constants_1_to_12(),
        case_node_name_and_value_matrix(),
        case_node_hierarchy_allowed_children(),
        case_books_xml_nodename_nodetype_nodevalue(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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