"""Offline XML DOM verification lab for Chapter 20 (nodes-clone)."""
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_deep_clone_and_append_book():
doc = minidom.parseString(BOOKS_XML)
x = doc.getElementsByTagName("book")[0]
cloned = x.cloneNode(True)
doc.documentElement.appendChild(cloned)
titles = [el.childNodes[0].nodeValue for el in doc.getElementsByTagName("title")]
expected = {
"book_count": 5,
"titles": [
"Everyday Italian",
"Harry Potter",
"XQuery Kick Start",
"Learning XML",
"Everyday Italian",
],
}
actual = {
"book_count": len(doc.getElementsByTagName("book")),
"titles": titles,
}
return {
"name": "deep_clone_and_append_book",
"summary": "使用 cloneNode(True) 深拷贝首本 book 并追加到根节点,验证输出 5 个书名与示例一致",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_shallow_clone_preserves_attrs_not_children():
doc = minidom.parseString(BOOKS_XML)
book0 = doc.getElementsByTagName("book")[0]
shallow = book0.cloneNode(False)
expected = {
"tag_name": "book",
"category_attr": "cooking",
"child_count": 0,
"parent_is_none": True,
}
actual = {
"tag_name": shallow.tagName,
"category_attr": shallow.getAttribute("category"),
"child_count": len(shallow.childNodes),
"parent_is_none": shallow.parentNode is None,
}
return {
"name": "shallow_clone_preserves_attrs_not_children",
"summary": "验证 cloneNode(False) 浅拷贝保留元素自身属性(category=cooking),但不复制任何子节点且父节点为空",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_clone_independence_from_original():
doc = minidom.parseString(BOOKS_XML)
orig = doc.getElementsByTagName("book")[0]
cloned = orig.cloneNode(True)
cloned.setAttribute("category", "dessert")
cloned.getElementsByTagName("title")[0].childNodes[0].nodeValue = "Italian Desserts"
doc.documentElement.appendChild(cloned)
expected = {
"orig_category": "cooking",
"orig_title": "Everyday Italian",
"cloned_category": "dessert",
"cloned_title": "Italian Desserts",
}
actual = {
"orig_category": orig.getAttribute("category"),
"orig_title": orig.getElementsByTagName("title")[0].childNodes[0].nodeValue,
"cloned_category": cloned.getAttribute("category"),
"cloned_title": cloned.getElementsByTagName("title")[0].childNodes[0].nodeValue,
}
return {
"name": "clone_independence_from_original",
"summary": "修改深拷贝节点的属性与后代文本,确认原节点及其子树完全独立不受影响",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_lxml_verify_cloned_document():
doc = minidom.parseString(BOOKS_XML)
cloned = doc.getElementsByTagName("book")[0].cloneNode(True)
doc.documentElement.appendChild(cloned)
lxml_root = etree.fromstring(doc.toxml().encode("utf-8"))
expected = {
"book_count": 5,
"titles": [
"Everyday Italian",
"Harry Potter",
"XQuery Kick Start",
"Learning XML",
"Everyday Italian",
],
}
actual = {
"book_count": len(lxml_root.findall("book")),
"titles": [el.text for el in lxml_root.findall("book/title")],
}
return {
"name": "lxml_verify_cloned_document",
"summary": "序列化深拷贝追加后的文档并由 lxml.etree 交叉核对 5 本书的完整结构与书名",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_deep_clone_and_append_book(),
case_shallow_clone_preserves_attrs_not_children(),
case_clone_independence_from_original(),
case_lxml_verify_cloned_document(),
]
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-clone-lab/explore-nodes-clone.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-nodes-clone.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2773.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip