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

实测 removeChild 删除元素/自身/文本、nodeValue 清空及两种属性删除方式

PYTHONWindows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。explore-nodes-remove.py
explore-nodes-remove.py169 行
"""Offline XML DOM verification lab for Chapter 16 (nodes-remove)."""
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_remove_element_and_self_via_parent():
    doc1 = minidom.parseString(BOOKS_XML)
    y = doc1.getElementsByTagName("book")[0]
    removed1 = doc1.documentElement.removeChild(y)
    remaining1 = [t.childNodes[0].nodeValue for t in doc1.getElementsByTagName("title")]

    doc2 = minidom.parseString(BOOKS_XML)
    x = doc2.getElementsByTagName("book")[0]
    removed2 = x.parentNode.removeChild(x)
    remaining2 = [t.childNodes[0].nodeValue for t in doc2.getElementsByTagName("title")]
    lxml_root = etree.fromstring(doc2.toxml().encode("utf-8"))
    expected = {
        "removed_tag": "book",
        "remaining_count": 3,
        "remaining_titles": ["Harry Potter", "XQuery Kick Start", "Learning XML"],
        "both_methods_equal": True,
        "lxml_book_count": 3,
    }
    actual = {
        "removed_tag": removed1.tagName,
        "remaining_count": len(remaining1),
        "remaining_titles": remaining1,
        "both_methods_equal": remaining1 == remaining2 and removed2.tagName == "book",
        "lxml_book_count": len(lxml_root.findall("book")),
    }
    return {
        "name": "remove_element_and_self_via_parent",
        "summary": "验证 documentElement.removeChild(y) 与 x.parentNode.removeChild(x) 删除元素节点及其全部子节点",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_remove_text_node_vs_clear_nodevalue():
    doc1 = minidom.parseString(BOOKS_XML)
    t1 = doc1.getElementsByTagName("title")[0]
    t1.removeChild(t1.childNodes[0])

    doc2 = minidom.parseString(BOOKS_XML)
    t2 = doc2.getElementsByTagName("title")[0]
    t2.childNodes[0].nodeValue = ""
    expected = {
        "after_remove_child_len": 0,
        "after_clear_nodevalue_len": 1,
        "cleared_text_value": "",
    }
    actual = {
        "after_remove_child_len": len(t1.childNodes),
        "after_clear_nodevalue_len": len(t2.childNodes),
        "cleared_text_value": t2.childNodes[0].nodeValue,
    }
    return {
        "name": "remove_text_node_vs_clear_nodevalue",
        "summary": "对比 removeChild 删除文本节点(childNodes 归零)与 nodeValue='' 清空文本(保留空文本节点)的差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_remove_attribute_by_name():
    doc = minidom.parseString(BOOKS_XML)
    books = doc.getElementsByTagName("book")
    books[0].removeAttribute("category")
    first_has_cat = books[0].hasAttribute("category")
    for b in books:
        if b.hasAttribute("category"):
            b.removeAttribute("category")
    remaining_attrs = [b.attributes.length for b in books]
    expected = {
        "first_has_category": False,
        "remaining_attr_counts": [0, 0, 0, 1],
        "fourth_keeps_cover": "paperback",
    }
    actual = {
        "first_has_category": first_has_cat,
        "remaining_attr_counts": remaining_attrs,
        "fourth_keeps_cover": books[3].getAttribute("cover"),
    }
    return {
        "name": "remove_attribute_by_name",
        "summary": "使用 removeAttribute('category') 删除单个及全部 book 的 category 属性,核对其他属性不受影响",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_remove_all_attribute_nodes_loop():
    doc = minidom.parseString(BOOKS_XML)
    books = doc.getElementsByTagName("book")
    before_total = sum(b.attributes.length for b in books)
    removed_names = []
    for b in books:
        while b.attributes.length > 0:
            attnode = b.attributes.item(0)
            old_att = b.removeAttributeNode(attnode)
            removed_names.append(old_att.nodeName)
    after_total = sum(b.attributes.length for b in books)
    expected = {
        "before_total_attrs": 5,
        "after_total_attrs": 0,
        "removed_count": 5,
    }
    actual = {
        "before_total_attrs": before_total,
        "after_total_attrs": after_total,
        "removed_count": len(removed_names),
    }
    return {
        "name": "remove_all_attribute_nodes_loop",
        "summary": "在 while 循环中使用 removeAttributeNode 删除全部 book 元素的全部属性节点,总数从 5 归零",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_remove_element_and_self_via_parent(),
        case_remove_text_node_vs_clear_nodevalue(),
        case_remove_attribute_by_name(),
        case_remove_all_attribute_nodes_loop(),
    ]
    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-remove-lab/explore-nodes-remove.py

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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