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

离线端到端复验全部 16 组 XML DOM 经典演练(解析/遍历/增删改查克隆/XHR)

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

VERSION = "CPython 3.12.14 offline XML DOM verifier (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="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
  </book>
</bookstore>
"""


def first_elem_child(el):
    cur = el.firstChild
    while cur is not None and cur.nodeType != Node.ELEMENT_NODE:
        cur = cur.nextSibling
    return cur


def last_elem_child(el):
    cur = el.lastChild
    while cur is not None and cur.nodeType != Node.ELEMENT_NODE:
        cur = cur.previousSibling
    return cur


def next_elem_sibling(el):
    cur = el.nextSibling
    while cur is not None and cur.nodeType != Node.ELEMENT_NODE:
        cur = cur.nextSibling
    return cur


def prev_elem_sibling(el):
    cur = el.previousSibling
    while cur is not None and cur.nodeType != Node.ELEMENT_NODE:
        cur = cur.previousSibling
    return cur


def case_examples_parse_access_info_traverse():
    doc = minidom.parseString(BOOKS_XML)
    titles = doc.getElementsByTagName("title")
    first_book = doc.getElementsByTagName("book")[0]
    raw_len = first_book.childNodes.length
    elem_children = [n for n in first_book.childNodes if n.nodeType == Node.ELEMENT_NODE]

    first_el = first_elem_child(first_book)
    last_el = last_elem_child(first_book)
    next_of_first = next_elem_sibling(first_el)
    prev_of_last = prev_elem_sibling(last_el)

    expected = {
        "titles_length": 2,
        "first_title_text": "Everyday Italian",
        "first_title_lang": "en",
        "first_book_category": "cooking",
        "raw_child_count_with_ws": 7,
        "element_child_tags": ["title", "author", "year"],
        "nav_parent_of_title": "book",
        "nav_first_last": ["title", "year"],
        "nav_next_prev_author": ["author", "author"],
    }
    actual = {
        "titles_length": titles.length,
        "first_title_text": titles.item(0).firstChild.nodeValue,
        "first_title_lang": titles.item(0).attributes.getNamedItem("lang").value,
        "first_book_category": first_book.getAttribute("category"),
        "raw_child_count_with_ws": raw_len,
        "element_child_tags": [n.nodeName for n in elem_children],
        "nav_parent_of_title": first_el.parentNode.nodeName,
        "nav_first_last": [first_el.nodeName, last_el.nodeName],
        "nav_next_prev_author": [next_of_first.nodeName, prev_of_last.nodeName],
    }
    return {
        "name": "examples_parse_access_info_traverse",
        "summary": "验证实例汇总第 1–8 组:解析加载、索引与 length 遍历、节点信息、空白文本过滤与父子同级导航",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_examples_get_set_remove_replace():
    doc = minidom.parseString(BOOKS_XML)
    books = doc.getElementsByTagName("book")
    b0 = books[0]

    title0 = b0.getElementsByTagName("title")[0]
    title0.firstChild.nodeValue = "Modern Italian"
    b0.setAttribute("category", "culinary")
    cat_attr = b0.getAttributeNode("category")
    cat_attr.nodeValue = "gourmet"

    year0 = b0.getElementsByTagName("year")[0]
    year0.firstChild.nodeValue = ""
    b0.removeChild(year0)
    b0.removeAttribute("category")

    b1 = books[1]
    cat_attr1 = b1.getAttributeNode("category")
    b1.removeAttributeNode(cat_attr1)
    new_author = doc.createElement("author")
    new_author.appendChild(doc.createTextNode("Updated Author"))
    old_author = b1.getElementsByTagName("author")[0]
    b1.replaceChild(new_author, old_author)

    t1 = b1.getElementsByTagName("title")[0].firstChild
    t1.data = t1.data.replace("Potter", "DOM")

    expected = {
        "b0_title": "Modern Italian",
        "b0_year_removed": True,
        "b0_category_removed": True,
        "b1_category_removed": True,
        "b1_replaced_author": "Updated Author",
        "b1_replaced_title_data": "Harry DOM",
    }
    actual = {
        "b0_title": title0.firstChild.nodeValue,
        "b0_year_removed": len(b0.getElementsByTagName("year")) == 0,
        "b0_category_removed": not b0.hasAttribute("category"),
        "b1_category_removed": not b1.hasAttribute("category"),
        "b1_replaced_author": b1.getElementsByTagName("author")[0].firstChild.nodeValue,
        "b1_replaced_title_data": t1.data,
    }
    return {
        "name": "examples_get_set_remove_replace",
        "summary": "验证实例汇总第 9–12 组:获取值、修改文本与属性、删除节点/属性与替换元素/文本数据",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_examples_create_add_clone():
    doc = minidom.parseString(BOOKS_XML)
    b0 = doc.getElementsByTagName("book")[0]

    edition = doc.createElement("edition")
    edition.appendChild(doc.createTextNode("First"))
    attr_obj = doc.createAttribute("format")
    attr_obj.value = "hardcover"
    edition.setAttributeNode(attr_obj)
    edition.setAttribute("isbn", "001")
    b0.appendChild(edition)

    summary = doc.createElement("summary")
    summary.appendChild(doc.createCDATASection("<b>Tasty & Quick</b>"))
    b0.insertBefore(summary, edition)

    cmt = doc.createComment("Checked")
    b0.appendChild(cmt)

    # Simulate insertData on text node
    ed_txt = edition.firstChild
    ed_txt.data = ed_txt.data[:5] + " Revised" + ed_txt.data[5:]

    cloned_book = b0.cloneNode(True)
    doc.documentElement.appendChild(cloned_book)

    expected = {
        "edition_text": "First Revised",
        "edition_attrs": ["hardcover", "001"],
        "cdata_preserved": "<b>Tasty & Quick</b>",
        "comment_text": "Checked",
        "book_count_after_clone": 3,
    }
    actual = {
        "edition_text": edition.firstChild.data,
        "edition_attrs": [edition.getAttribute("format"), edition.getAttribute("isbn")],
        "cdata_preserved": summary.firstChild.data,
        "comment_text": cmt.data,
        "book_count_after_clone": len(doc.getElementsByTagName("book")),
    }
    return {
        "name": "examples_create_add_clone",
        "summary": "验证实例汇总第 13–15 组:创建元素/属性/文本/CDATA/注释、append/insertBefore 与 cloneNode",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_examples_xhr_scenarios_summary():
    headers = {
        "Content-Type": "application/xml",
        "Last-Modified": "Tue, 01 Dec 2026 09:00:00 GMT",
    }
    doc = minidom.parseString(BOOKS_XML)
    rows = [
        (b.getElementsByTagName("title")[0].firstChild.data, b.getElementsByTagName("author")[0].firstChild.data)
        for b in doc.getElementsByTagName("book")
    ]
    suggestions = [t for t, _ in rows if t.startswith("H")]
    html_table = "<table>" + "".join(f"<tr><td>{t}</td><td>{a}</td></tr>" for t, a in rows) + "</table>"

    expected = {
        "header_count": 2,
        "last_modified": "Tue, 01 Dec 2026 09:00:00 GMT",
        "suggestions": ["Harry Potter"],
        "table_has_two_rows": True,
    }
    actual = {
        "header_count": len(headers),
        "last_modified": headers["Last-Modified"],
        "suggestions": suggestions,
        "table_has_two_rows": html_table.count("<tr>") == 2,
    }
    return {
        "name": "examples_xhr_scenarios_summary",
        "summary": "验证实例汇总第 16 组 XMLHttpRequest 场景:文本与响应头检索、动态建议、数据库与 XML 表格渲染",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_examples_parse_access_info_traverse(),
        case_examples_get_set_remove_replace(),
        case_examples_create_add_clone(),
        case_examples_xhr_scenarios_summary(),
    ]
    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-xml-dom-examples-lab/explore-xml-dom-examples.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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