XML DOM 创建节点
系统讲解 Document 工厂方法创建各类 XML 节点:createElement()、createAttribute()/setAttribute()、createTextNode()、createCDATASection() 与 createComment(),并说明正确大小写与挂载步骤。
学完这一章,你能够
- 系统讲解 Document 工厂方法创建各类 XML 节点:createElement()、createAttribute()/setAttribute()、createTextNode()、createCDATASection() 与 createComment(),并说明正确大小写与挂载步骤。
创建元素节点与文本节点
在 XML DOM 中,所有新节点均由所属文档对象 `xmlDoc` 的工厂方法创建,随后再挂载到目标父元素上。围绕 `books.xml`,核心创建方法覆盖六种高频操作:创建元素节点(`createElement()`)、用 `createAttribute()` 与 `setAttributeNode()` 创建并绑定属性节点、用 `setAttribute()` 直接创建属性、创建文本节点(`createTextNode()`)、创建 CDATA 区段节点(注意标准大小写拼写为 `createCDATASection()`,切勿将 `S` 误写为小写)以及创建注释节点(`createComment()`)。
`xmlDoc.createElement("edition")` 会生成一个名为 `<edition>` 的空元素节点,但此时它尚未进入文档树;只有继续调用目标父元素(如第一个 `<book>`)的 `appendChild(newel)`,该元素才会正式成为文档树的一部分。结合循环即可为所有 `<book>` 依次追加 `<edition>`。
若新元素需要携带文字内容,须再调用 `createTextNode("first")` 创建文本节点,先通过 `newel.appendChild(newtext)` 将文本挂载至 `<edition>`,最后将完整的 `<edition>first</edition>` 追加到第一个(或全部)`<book>` 元素下。
创建属性节点:createAttribute() 与 setAttribute()
通过 `createAttribute("edition")` 可先创建独立属性节点对象 `newatt`,随后设置 `newatt.nodeValue = "first"`,再调用目标元素(如首个 `<title>`)的 `setAttributeNode(newatt)` 完成绑定;循环执行即可为全部 `<title>` 添加该属性节点。若目标元素上已存在同名属性,新属性节点将自动替代旧属性。
相比三步式 `createAttribute()`,直接调用 `x[0].setAttribute("edition", "first")` 更为简洁:只要该属性尚不存在,`setAttribute()` 就会自动完成创建与赋值;同样可在循环中批量为所有 `<title>` 元素添加新属性。
创建 CDATA 区段节点与注释节点
`xmlDoc.createCDATASection("Special Offer & Book Sale")` 用于创建 CDATA 区段节点(`nodeType === 4`,`nodeName === "#cdata-section"`),将其通过 `appendChild()` 追加到首个(或全部)`<book>` 后,序列化时会以 `<![CDATA[Special Offer & Book Sale]]>` 形式保留原始 `&` 或 `<` 字符而不作实体转义。
`xmlDoc.createComment("Revised March 2008")` 用于创建 XML 注释节点(`nodeType === 8`,`nodeName === "#comment"`),同样需经 `appendChild()` 追加到第一个(或所有)`<book>` 元素下,序列化输出为 `<!--Revised March 2008-->`。
实测创建元素、文本、属性、CDATA 区段与注释节点并验证序列化输出
"""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()
- 确认五类节点工厂方法均生成正确 nodeType(1/2/3/4/8),CDATA 保留未转义 '&',注释节点序列化后可由 lxml.etree 完整还原。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
当前源码 SHA256:84589ce1d01eefbfcb85aa7c2ca773b8b7217832b256bea06e8d2ebdea72d260
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
ZIP SHA256:e2322866c8d8da961fa49f73e6299138d62bb4a8b722cae248a8c4bf710d852a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 XML 文档中,什么时候应当使用 `createCDATASection()` 而不是 `createTextNode()`?
展开参考解答
当需要嵌入包含大量 `&`、`<` 等特殊字符(例如代码片段、数学表达式或脚本片段)且希望序列化结果保持原文不转义为 `&`、`<` 时,适合使用 `createCDATASection()`(注意文本本身不得包含 `]]>` 结束定界符)。