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

离线以 lxml.etree 与 xml.sax 核验 DOM、SAX、XPath 及 XSLT 转换语义

PYTHONWindows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。explore-xml-xslt-xpath.py
explore-xml-xslt-xpath.py167 行
"""Offline Ruby 3.x semantic verification lab for Chapter 41 (xml-xslt-xpath)."""
import json
import xml.sax
from lxml import etree

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (lxml.etree + xml.sax, MRI ruby absent)"

MOVIES_XML = """<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A scientific fiction</description>
</movie>
<movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>"""


def case_rexml_dom_tree_traversal():
    root = etree.fromstring(MOVIES_XML.encode("utf-8"))
    shelf = root.attrib["shelf"]
    titles = [m.attrib["title"] for m in root.findall("movie")]
    types = [e.text for e in root.findall("movie/type")]
    descs = [e.text for e in root.findall("movie/description")]
    expected = {
        "shelf": "New Arrivals",
        "titles": ["Enemy Behind", "Transformers", "Trigun", "Ishtar"],
        "types": ["War, Thriller", "Anime, Science Fiction", "Anime, Action", "Comedy"],
        "desc_count": 4,
    }
    actual = {
        "shelf": shelf,
        "titles": titles,
        "types": types,
        "desc_count": len(descs),
    }
    return {
        "name": "rexml_dom_tree_traversal",
        "summary": "核验 REXML DOM 解析模型读取根属性 shelf 与 movie/type/description 子节点文本",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rexml_sax_stream_events():
    class Listener(xml.sax.ContentHandler):
        def __init__(self):
            self.starts = []
            self.non_ws_texts = []

        def startElement(self, name, attrs):
            self.starts.append((name, dict(attrs)))

        def characters(self, content):
            s = content.strip()
            if s:
                self.non_ws_texts.append(s)

    handler = Listener()
    xml.sax.parseString(MOVIES_XML.encode("utf-8"), handler)
    expected = {
        "first_tag": ["collection", {"shelf": "New Arrivals"}],
        "movie_start_count": 4,
        "captured_first_type": "War, Thriller",
    }
    actual = {
        "first_tag": [handler.starts[0][0], handler.starts[0][1]],
        "movie_start_count": sum(1 for tag, _ in handler.starts if tag == "movie"),
        "captured_first_type": handler.non_ws_texts[0],
    }
    return {
        "name": "rexml_sax_stream_events",
        "summary": "核验 SAX 流式事件解析按顺序触发 tag_start 与文本回调,无需整树常驻内存",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rexml_xpath_queries():
    doc = etree.fromstring(MOVIES_XML.encode("utf-8"))
    first_movie = doc.xpath("//movie")[0].attrib["title"]
    all_types = doc.xpath("//type/text()")
    all_formats = doc.xpath("//format/text()")
    high_rated = doc.xpath("//movie[stars='10']/@title")
    expected = {
        "xpath_first_movie": "Enemy Behind",
        "xpath_types": ["War, Thriller", "Anime, Science Fiction", "Anime, Action", "Comedy"],
        "xpath_formats": ["DVD", "DVD", "DVD", "VHS"],
        "ten_star_titles": ["Enemy Behind", "Trigun"],
    }
    actual = {
        "xpath_first_movie": first_movie,
        "xpath_types": all_types,
        "xpath_formats": all_formats,
        "ten_star_titles": high_rated,
    }
    return {
        "name": "rexml_xpath_queries",
        "summary": "核验 XPath.first('//movie')、XPath.each('//type')、XPath.match('//format') 与条件谓词查询",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_xslt_transform_with_lxml():
    xsl = etree.XML(
        """<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="xml" omit-xml-declaration="yes"/>
        <xsl:template match="/collection">
            <titles><xsl:for-each select="movie"><item><xsl:value-of select="@title"/></item></xsl:for-each></titles>
        </xsl:template>
        </xsl:stylesheet>"""
    )
    transform = etree.XSLT(xsl)
    result = transform(etree.fromstring(MOVIES_XML.encode("utf-8")))
    items = [el.text for el in result.getroot().findall("item")]
    expected = {"transformed_titles": ["Enemy Behind", "Transformers", "Trigun", "Ishtar"]}
    actual = {"transformed_titles": items}
    return {
        "name": "xslt_transform_with_lxml",
        "summary": "使用 lxml XSLT 处理器核验样式表将 movies.xml 转换为精简标题 XML 树",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_rexml_dom_tree_traversal(),
        case_rexml_sax_stream_events(),
        case_rexml_xpath_queries(),
        case_xslt_transform_with_lxml(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。

入口文件:projects/ruby-xml-xslt-xpath-lab/explore-xml-xslt-xpath.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-xml-xslt-xpath.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Ruby

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

下载课程关联工程包:Ruby

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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