XML DOM 节点
阐明 DOM 将 XML 文档中每种成分均抽象为节点的核心规则,剖析标准示例 books.xml 的层级构成,并强调文本始终存放在文本节点中而非元素节点本身。
学完这一章,你能够
- 阐明 DOM 将 XML 文档中每种成分均抽象为节点的核心规则,剖析标准示例 books.xml 的层级构成,并强调文本始终存放在文本节点中而非元素节点本身。
一切成分皆节点
在 DOM 模型中,XML 文档里的每一种语法成分都被表示为一个节点对象。按照 DOM 规定:整份 XML 文档本身是一个文档节点(Document Node);每一个 XML 标签对构成一个元素节点(Element Node);元素标签内部包含的文字内容是文本节点(Text Node);写在开始标签里的每个 XML 属性是一个属性节点(Attribute Node);文档中的 XML 注释则是注释节点(Comment Node)。
标准示例 books.xml 的节点结构剖析
后续多数章节都将以经典的书店目录文件 `books.xml` 作为演示数据。该文件以 `<?xml version="1.0" encoding="UTF-8"?>` 声明开头,根标签 `<bookstore>` 内依次存放四本图书记录,涵盖单作者、多作者(第三本书包含五位 `<author>`)以及多属性(第四本书同时带有 `category="web"` 和 `cover="paperback"`)等典型 XML 结构。
在 `books.xml` 中,根元素节点 `<bookstore>` 包裹了文档内的其余所有元素内容,其下直接包含四个 `<book>` 元素节点。以第一个 `<book>` 为例,它下辖 `<title>`、`<author>`、`<year>` 和 `<price>` 四个子元素节点,而这四个子元素又各自包含一个文本节点,内容依次为 `"Everyday Italian"`、`"Giada De Laurentiis"`、`"2005"` 和 `"30.00"`。
关键认知:文本总是存储在文本节点中
初学者在编写 DOM 代码时最容易犯的一个错误,是以为元素节点自身直接存放着字符串文本。事实上,元素节点的文本内容总是存储在它的子文本节点之中:以 `<year>2005</year>` 为例,`<year>` 元素节点本身的 `nodeValue` 为空(`null` / `None`),它拥有一个独立的子文本节点,该文本节点的 `nodeValue` 才是 `"2005"`——换句话说,`"2005"` 并不是 `<year>` 元素节点的值。
解析完整 books.xml 并验证五类 DOM 节点与文本节点归属规则
"""Offline XML DOM verification lab for Chapter 03 (nodes)."""
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>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</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_five_core_node_kinds():
sample = '<?xml version="1.0" encoding="UTF-8"?><bookstore><!-- catalog --><book category="cooking"><year>2005</year></book></bookstore>'
doc = minidom.parseString(sample)
comment = doc.documentElement.childNodes[0]
book = doc.documentElement.childNodes[1]
attr = book.getAttributeNode("category")
text = book.firstChild.firstChild
expected = {
"document_type": 9,
"element_type": 1,
"text_type": 3,
"attribute_type": 2,
"comment_type": 8,
"comment_data": " catalog ",
}
actual = {
"document_type": doc.nodeType,
"element_type": book.nodeType,
"text_type": text.nodeType,
"attribute_type": attr.nodeType,
"comment_type": comment.nodeType,
"comment_data": comment.nodeValue,
}
return {
"name": "five_core_node_kinds",
"summary": "验证 XML 文档中文档、元素、文本、属性、注释五类核心 DOM 节点的 nodeType",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_books_xml_structure_inspection():
doc = minidom.parseString(BOOKS_XML)
books = doc.getElementsByTagName("book")
third_authors = [a.firstChild.nodeValue for a in books[2].getElementsByTagName("author")]
lxml_root = etree.fromstring(BOOKS_XML.encode("utf-8"))
expected = {
"root_name": "bookstore",
"book_count": 4,
"third_book_author_count": 5,
"fourth_book_cover": "paperback",
"lxml_book_count": 4,
}
actual = {
"root_name": doc.documentElement.tagName,
"book_count": len(books),
"third_book_author_count": len(third_authors),
"fourth_book_cover": books[3].getAttribute("cover"),
"lxml_book_count": len(lxml_root.findall("book")),
}
return {
"name": "books_xml_structure_inspection",
"summary": "解析完整 books.xml,核对根元素 bookstore、4 本书、第 3 本书 5 位作者与第 4 本书 cover 属性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_first_book_children_and_text_nodes():
doc = minidom.parseString(BOOKS_XML)
book0 = doc.getElementsByTagName("book")[0]
elems = [n for n in book0.childNodes if n.nodeType == n.ELEMENT_NODE]
pairs = [(e.tagName, e.firstChild.nodeValue) for e in elems]
expected = [
("title", "Everyday Italian"),
("author", "Giada De Laurentiis"),
("year", "2005"),
("price", "30.00"),
]
actual = pairs
return {
"name": "first_book_children_and_text_nodes",
"summary": "核对第一个 book 节点的 4 个子元素及其对应文本节点内容",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_text_stored_in_text_node_not_element():
doc = minidom.parseString(BOOKS_XML)
year_elem = doc.getElementsByTagName("year")[0]
year_text = year_elem.firstChild
expected = {
"element_node_name": "year",
"element_node_value_is_none": True,
"child_node_name": "#text",
"child_node_type": 3,
"child_node_value": "2005",
}
actual = {
"element_node_name": year_elem.nodeName,
"element_node_value_is_none": year_elem.nodeValue is None,
"child_node_name": year_text.nodeName,
"child_node_type": year_text.nodeType,
"child_node_value": year_text.nodeValue,
}
return {
"name": "text_stored_in_text_node_not_element",
"summary": "验证 <year>2005</year> 中元素节点的 nodeValue 为空,文本 '2005' 实际存放在子文本节点中",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_five_core_node_kinds(),
case_books_xml_structure_inspection(),
case_first_book_children_and_text_nodes(),
case_text_stored_in_text_node_not_element(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 确认 Document/Element/Text/Attribute/Comment 五类 nodeType 正确,books.xml 含 4 本书与首书 4 个子元素文本,且 <year> 元素 nodeValue 为 None、其子文本节点值为 '2005'。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
当前源码 SHA256:f59bd218bfbda97f3046a885d413a6a911b8fc9f608a14bfe56a8fdac4e0f2fd
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
ZIP SHA256:33f0e0ffc7d80ee33f080dba0478463649a9305e90e521f3e05d65286cb8e831
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么对 `<year>2005</year>` 元素节点直接读取 `yearNode.nodeValue` 拿不到 `"2005"`?
展开参考解答
因为按 W3C DOM 规范,元素节点的 `nodeValue` 恒为 `null`(Python 中为 `None`),字符串 `"2005"` 存储在 `<year>` 的第一个子节点(文本节点)的 `nodeValue` 中。