XML DOM 添加节点
系统说明向 XML DOM 树中挂载节点与数据的四种方式:appendChild() 末尾追加、insertBefore() 指定位置插入(含第二个参数为 null 的行为)、setAttribute() 添加属性以及 insertData() 向文本节点插入字符串。
学完这一章,你能够
- 系统说明向 XML DOM 树中挂载节点与数据的四种方式:appendChild() 末尾追加、insertBefore() 指定位置插入(含第二个参数为 null 的行为)、setAttribute() 添加属性以及 insertData() 向文本节点插入字符串。
末尾追加与指定位置插入:appendChild() 与 insertBefore()
创建节点后需通过专门的添加接口将其放入文档树。围绕 `books.xml`,四种核心添加操作分别是:使用 `appendChild()` 在末尾追加子节点、使用 `insertBefore()` 在指定子节点之前精确插入、使用 `setAttribute()` 添加新属性,以及使用 `insertData()` 向已有文本节点中插入字符串。
`appendChild(node)` 会把新节点添加到父节点所有已有子节点的最后面。例如创建 `<edition>` 并调用首个 `<book>` 的 `x.appendChild(newel)`,`<edition>` 就会排在 `<price>` 之后;循环调用即可向所有 `<book>` 末尾追加元素。如果节点在兄弟之间的排列顺序十分重要,则应改用 `insertBefore()`。
`parent.insertBefore(newNode, referenceNode)` 用于在指定参考子节点 `referenceNode` 之前插入 `newNode`。例如载入 `books.xml` 后创建新 `<book>` 元素,并取得索引为 `3` 的第四本 `<book>` 作为参考节点 `y`,调用 `x.insertBefore(newNode, y)` 即可把新书插到最后一本书之前。此外,当第二个参数传入 `null`(Python 中为 `None`)时,`x.insertBefore(newNode, null)` 的效果与 `x.appendChild(newNode)` 完全等价,都会将新节点追加到子节点列表末尾。
添加新属性与向文本节点插入字符
XML DOM 中并不存在名为 `addAttribute()` 的方法。要为元素新增属性,只需直接调用 `setAttribute(name, value)`:对首个 `<book>` 执行 `x[0].setAttribute("edition", "first")` 会在 `edition` 不存在时创建该属性;需留意若同名属性已存在,`setAttribute()` 会直接覆盖原有值。
若希望保留文本节点原有内容并在指定位置插入新字符,可调用 `insertData(offset, string)`:其中 `offset` 为从 `0` 开始的插入位置索引,`string` 为待插入文本。对首个 `<title>` 的文本节点 `"Everyday Italian"` 执行 `x.insertData(0, "Easy ")`,即可在最前方插入前缀得到 `"Easy Everyday Italian"`(注:若要在末尾追加,浏览器 DOM 允许 `offset === length`,而在 Python `xml.dom.minidom` 中 `insertData` 要求 `offset < len(data)`,尾部追加应使用同属 `CharacterData` 接口的 `appendData()`)。
实测 appendChild、insertBefore(含 null 尾插)、setAttribute 与 insertData/appendData
"""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()
- 确认 appendChild 末尾追加、insertBefore 精确插入与 None 等价尾插、无 addAttribute 方法而由 setAttribute 增改属性,以及 insertData/appendData 字符串拼接均准确通过。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
当前源码 SHA256:c1a1e33571add6ee67de29217f63b25029216c28642c539044883388063b7256
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
ZIP SHA256:b73b82d911ea9d4f955e99dc9b0966dc5cd33fc7850fe65434211bbbbb4e0b48
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`x.insertBefore(newNode, null)` 与 `x.appendChild(newNode)` 的执行结果有何区别?
展开参考解答
两者执行结果完全相同:当 `insertBefore()` 的第二个参数为 `null`(Python 中为 `None`)时,新节点会被追加到 `x` 的所有已有子节点末尾。