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

实测 appendChild、insertBefore(含 null 尾插)、setAttribute 与 insertData/appendData

PYTHONWindows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。explore-nodes-add.py
explore-nodes-add.py159 行
"""Offline XML DOM verification lab for Chapter 19 (nodes-add)."""
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>
        <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_append_child_to_end():
    doc = minidom.parseString(BOOKS_XML)
    newel = doc.createElement("edition")
    book0 = doc.getElementsByTagName("book")[0]
    book0.appendChild(newel)
    elem_kids = [n.tagName for n in book0.childNodes if n.nodeType == 1]
    expected = {
        "book0_elements": ["title", "author", "year", "price", "edition"],
        "last_child_is_edition": True,
    }
    actual = {
        "book0_elements": elem_kids,
        "last_child_is_edition": book0.lastChild.tagName == "edition",
    }
    return {
        "name": "append_child_to_end",
        "summary": "使用 appendChild 将新创建的 edition 元素追加到第一个 book 元素的末尾",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_insert_before_target_and_null():
    doc = minidom.parseString(BOOKS_XML)
    root = doc.documentElement
    inserted = doc.createElement("book")
    inserted.setAttribute("category", "inserted")
    target = doc.getElementsByTagName("book")[3]
    root.insertBefore(inserted, target)
    appended = doc.createElement("book")
    appended.setAttribute("category", "tail")
    root.insertBefore(appended, None)
    cats = [b.getAttribute("category") for b in doc.getElementsByTagName("book")]
    lxml_cats = [b.get("category") for b in etree.fromstring(doc.toxml().encode("utf-8")).findall("book")]
    expected = {
        "book_count": 6,
        "categories": ["cooking", "children", "web", "inserted", "web", "tail"],
        "matches_lxml": True,
    }
    actual = {
        "book_count": len(cats),
        "categories": cats,
        "matches_lxml": cats == lxml_cats,
    }
    return {
        "name": "insert_before_target_and_null",
        "summary": "验证 insertBefore(newNode, y) 插入到目标子节点之前,以及第二个参数为 None/null 时等价于 appendChild",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_add_new_attribute_via_set_attribute():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    has_add_attr = hasattr(book0, "addAttribute")
    book0.setAttribute("edition", "first")
    first_val = book0.getAttribute("edition")
    book0.setAttribute("edition", "second")
    overwritten_val = book0.getAttribute("edition")
    expected = {
        "has_addAttribute_method": False,
        "created_value": "first",
        "overwritten_value": "second",
    }
    actual = {
        "has_addAttribute_method": has_add_attr,
        "created_value": first_val,
        "overwritten_value": overwritten_val,
    }
    return {
        "name": "add_new_attribute_via_set_attribute",
        "summary": "确认不存在 addAttribute 方法,使用 setAttribute 新增属性并在重复调用时覆盖已有值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_insert_data_into_text_node():
    doc = minidom.parseString(BOOKS_XML)
    text_node = doc.getElementsByTagName("title")[0].childNodes[0]
    text_node.insertData(0, "Easy ")
    after_prefix = text_node.nodeValue
    text_node.insertData(5, "Classic ")
    after_middle = text_node.nodeValue
    text_node.appendData(" Recipes")
    after_append = text_node.nodeValue
    expected = {
        "after_prefix": "Easy Everyday Italian",
        "after_middle": "Easy Classic Everyday Italian",
        "after_append": "Easy Classic Everyday Italian Recipes",
    }
    actual = {
        "after_prefix": after_prefix,
        "after_middle": after_middle,
        "after_append": after_append,
    }
    return {
        "name": "insert_data_into_text_node",
        "summary": "调用文本节点 insertData(0, 'Easy ') 在开头插入前缀,并验证中间偏移插入与 appendData 尾部追加",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_append_child_to_end(),
        case_insert_before_target_and_null(),
        case_add_new_attribute_via_set_attribute(),
        case_insert_data_into_text_node(),
    ]
    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-add-lab/explore-nodes-add.py

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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