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

运行真实 SAX、DOM(minidom)、Pull(iterparse) 三种 XML 解析与 UTF-8 序列化往返实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-xml.py
explore-tutorial-xml.py185 行
"""Offline Android XML parsing (SAX, DOM, Pull/iterparse) & serialization verifier (Ch 89: tutorial-xml)."""
from __future__ import annotations

import io
import json
import sys
import xml.dom.minidom as minidom
import xml.etree.ElementTree as ET
import xml.sax
from xml.sax.handler import ContentHandler

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"

SAMPLE_XML = """<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="11">
        <name>SAX解析</name>
        <age>18</age>
    </person>
    <person id="13">
        <name>XML1</name>
        <age>43</age>
    </person>
</persons>
"""


class PersonSaxHandler(ContentHandler):
    def __init__(self) -> None:
        super().__init__()
        self.persons: list[dict] = []
        self._current: dict | None = None
        self._tag: str | None = None
        self._buf: list[str] = []
        self.whitespace_callbacks = 0
        self.events: list[str] = []

    def startDocument(self) -> None:
        self.events.append("startDocument")

    def startElement(self, name: str, attrs) -> None:
        if name == "person":
            self._current = {"id": int(attrs["id"]), "name": "", "age": 0}
        self._tag = name
        self._buf = []

    def characters(self, content: str) -> None:
        if content.strip() == "":
            self.whitespace_callbacks += 1
        if self._tag in {"name", "age"}:
            self._buf.append(content)

    def endElement(self, name: str) -> None:
        if self._current is not None and name in {"name", "age"}:
            text = "".join(self._buf).strip()
            if name == "name":
                self._current["name"] = text
            elif name == "age":
                self._current["age"] = int(text)
        elif name == "person" and self._current is not None:
            self.persons.append(self._current)
            self._current = None
        self._tag = None
        self._buf = []

    def endDocument(self) -> None:
        self.events.append("endDocument")


def parse_with_dom(xml_text: str) -> list[dict]:
    doc = minidom.parseString(xml_text.encode("utf-8"))
    out = []
    for p_el in doc.getElementsByTagName("person"):
        item = {"id": int(p_el.getAttribute("id")), "name": "", "age": 0}
        for child in p_el.childNodes:
            if child.nodeType == child.ELEMENT_NODE:
                if child.nodeName == "name" and child.firstChild:
                    item["name"] = child.firstChild.nodeValue
                elif child.nodeName == "age" and child.firstChild:
                    item["age"] = int(child.firstChild.nodeValue)
        out.append(item)
    return out


def parse_with_pull(xml_text: str) -> list[dict]:
    """Pull-style streaming parse via ElementTree.iterparse (start/end events)."""
    out: list[dict] = []
    current: dict | None = None
    for event, elem in ET.iterparse(io.BytesIO(xml_text.encode("utf-8")), events=("start", "end")):
        if event == "start" and elem.tag == "person":
            current = {"id": int(elem.attrib["id"]), "name": "", "age": 0}
        elif event == "end":
            if current is not None and elem.tag == "name":
                current["name"] = elem.text or ""
            elif current is not None and elem.tag == "age":
                current["age"] = int(elem.text or "0")
            elif elem.tag == "person" and current is not None:
                out.append(current)
                current = None
                elem.clear()
    return out


def serialize_persons_xml(persons: list[dict]) -> str:
    root = ET.Element("persons")
    for p in persons:
        pe = ET.SubElement(root, "person", id=str(p["id"]))
        ET.SubElement(pe, "name").text = p["name"]
        ET.SubElement(pe, "age").text = str(p["age"])
    buf = io.BytesIO()
    ET.ElementTree(root).write(buf, encoding="UTF-8", xml_declaration=True)
    return buf.getvalue().decode("utf-8")


def main() -> None:
    expected_persons = [
        {"id": 11, "name": "SAX解析", "age": 18},
        {"id": 13, "name": "XML1", "age": 43},
    ]
    cases = []

    # Case 1: SAX event-driven parsing + whitespace node observation
    handler = PersonSaxHandler()
    xml.sax.parseString(SAMPLE_XML.encode("utf-8"), handler)
    actual1 = {
        "persons": handler.persons,
        "lifecycle": handler.events,
        "saw_whitespace_text_nodes": handler.whitespace_callbacks > 0,
    }
    expected1 = {
        "persons": expected_persons,
        "lifecycle": ["startDocument", "endDocument"],
        "saw_whitespace_text_nodes": True,
    }
    cases.append({
        "name": "sax_event_driven_parsing",
        "summary": "Verify xml.sax ContentHandler startDocument/startElement/characters/endElement/endDocument and whitespace callbacks.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: DOM tree parsing with ELEMENT_NODE filtering
    dom_persons = parse_with_dom(SAMPLE_XML)
    cases.append({
        "name": "dom_tree_parsing",
        "summary": "Verify xml.dom.minidom tree construction, getElementsByTagName, and ELEMENT_NODE child filtering.",
        "expected": expected_persons,
        "actual": dom_persons,
        "passed": dom_persons == expected_persons,
    })

    # Case 3: Pull-style iterparse streaming parser
    pull_persons = parse_with_pull(SAMPLE_XML)
    cases.append({
        "name": "pull_streaming_parsing",
        "summary": "Verify Pull-style incremental XML parsing via ElementTree.iterparse with element clearing.",
        "expected": expected_persons,
        "actual": pull_persons,
        "passed": pull_persons == expected_persons,
    })

    # Case 4: XmlSerializer-style generation and full round-trip verification
    generated_xml = serialize_persons_xml(expected_persons)
    reparsed = parse_with_pull(generated_xml)
    actual4 = {
        "has_utf8_decl": "UTF-8" in generated_xml.splitlines()[0].upper(),
        "roundtrip_equal": reparsed == expected_persons,
        "count": len(reparsed),
    }
    expected4 = {"has_utf8_decl": True, "roundtrip_equal": True, "count": 2}
    cases.append({
        "name": "xml_serializer_roundtrip",
        "summary": "Verify UTF-8 XML serialization (XmlSerializer pattern) and Pull round-trip equivalence.",
        "expected": expected4,
        "actual": actual4,
        "passed": actual4 == expected4,
    })

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-xml-lab/explore-tutorial-xml.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-xml.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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