"""Offline XML DOM verification lab for Chapter 18 (nodes-create)."""
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_create_element_and_text_node():
doc = minidom.parseString(BOOKS_XML)
for book in doc.getElementsByTagName("book"):
newel = doc.createElement("edition")
newtext = doc.createTextNode("first")
newel.appendChild(newtext)
book.appendChild(newel)
editions = [el.childNodes[0].nodeValue for el in doc.getElementsByTagName("edition")]
expected = {
"edition_count": 4,
"edition_values": ["first", "first", "first", "first"],
"first_edition_node_type": 1,
"first_text_node_type": 3,
}
actual = {
"edition_count": len(editions),
"edition_values": editions,
"first_edition_node_type": doc.getElementsByTagName("edition")[0].nodeType,
"first_text_node_type": doc.getElementsByTagName("edition")[0].firstChild.nodeType,
}
return {
"name": "create_element_and_text_node",
"summary": "使用 createElement('edition') 与 createTextNode('first') 为各 book 追加新元素与文本节点",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_create_attribute_vs_set_attribute():
doc = minidom.parseString(BOOKS_XML)
newatt = doc.createAttribute("edition")
newatt.nodeValue = "first"
title0 = doc.getElementsByTagName("title")[0]
title0.setAttributeNode(newatt)
# Overwrite existing attribute via setAttributeNode
newatt2 = doc.createAttribute("edition")
newatt2.nodeValue = "second"
title0.setAttributeNode(newatt2)
# Create via setAttribute on book
book0 = doc.getElementsByTagName("book")[0]
book0.setAttribute("edition", "first")
expected = {
"attr_node_type": 2,
"title0_overwritten_edition": "second",
"book0_set_attribute_edition": "first",
}
actual = {
"attr_node_type": newatt.nodeType,
"title0_overwritten_edition": title0.getAttribute("edition"),
"book0_set_attribute_edition": book0.getAttribute("edition"),
}
return {
"name": "create_attribute_vs_set_attribute",
"summary": "对比 createAttribute+setAttributeNode(含同名属性替换)与 setAttribute 直接创建属性的用法",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_create_cdata_section_node():
doc = minidom.parseString(BOOKS_XML)
cdata = doc.createCDATASection("Special Offer & Book Sale")
book0 = doc.getElementsByTagName("book")[0]
book0.appendChild(cdata)
xml_out = book0.toxml()
expected = {
"node_type": 4,
"node_name": "#cdata-section",
"node_value": "Special Offer & Book Sale",
"serialized_has_raw_cdata": True,
}
actual = {
"node_type": cdata.nodeType,
"node_name": cdata.nodeName,
"node_value": cdata.nodeValue,
"serialized_has_raw_cdata": "<![CDATA[Special Offer & Book Sale]]>" in xml_out,
}
return {
"name": "create_cdata_section_node",
"summary": "调用 createCDATASection 创建 CDATA 节点,验证 nodeType=4 及序列化中 '&' 不被转义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_create_comment_node():
doc = minidom.parseString(BOOKS_XML)
comment = doc.createComment("Revised March 2008")
book0 = doc.getElementsByTagName("book")[0]
book0.appendChild(comment)
xml_str = doc.toxml()
lxml_root = etree.fromstring(xml_str.encode("utf-8"))
comments = [n.text for n in lxml_root.find("book") if isinstance(n, etree._Comment)]
expected = {
"node_type": 8,
"node_name": "#comment",
"node_value": "Revised March 2008",
"lxml_parsed_comments": ["Revised March 2008"],
}
actual = {
"node_type": comment.nodeType,
"node_name": comment.nodeName,
"node_value": comment.nodeValue,
"lxml_parsed_comments": comments,
}
return {
"name": "create_comment_node",
"summary": "调用 createComment 创建注释节点追加到首书,并经由 lxml.etree 重新解析验证注释内容",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_create_element_and_text_node(),
case_create_attribute_vs_set_attribute(),
case_create_cdata_section_node(),
case_create_comment_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-create-lab/explore-nodes-create.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-nodes-create.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2774.zip