XML DOM 导航节点
系统讲解利用 parentNode、childNodes、firstChild、lastChild、nextSibling 与 previousSibling 进行节点树导航,示范跳过空白文本节点的安全封装函数,并介绍现代元素导航属性。
学完这一章,你能够
- 系统讲解利用 parentNode、childNodes、firstChild、lastChild、nextSibling 与 previousSibling 进行节点树导航,示范跳过空白文本节点的安全封装函数,并介绍现代元素导航属性。
节点关系属性与父节点导航
沿着节点之间的层级与同级关联在节点树中移动定位,通常称为导航节点(Navigating Nodes)。XML DOM 通过六个标准关系属性表达节点关联:`parentNode`、`childNodes`、`firstChild`、`lastChild`、`nextSibling` 和 `previousSibling`,它们完整刻画了 `books.xml` 中父子与前后兄弟之间的链接结构。
除文档根节点外,树中的每个节点都拥有唯一一个父节点。载入 `books.xml` 后,取第一个 `<book>` 元素存入 `x`,访问 `x.parentNode.nodeName` 即可向上导航并输出其父元素名称 `bookstore`。
跳过空白文本节点的安全导航封装
由于遵循 W3C 标准的浏览器会把换行与缩进视为文本节点(而旧版 IE 不会),直接调用 `firstChild`、`lastChild`、`nextSibling` 或 `previousSibling` 时往往会先落在空白文本节点上。经典跨浏览器解法是编写检查 `nodeType` 的辅助函数——例如 `get_nextSibling(n)` 从 `n.nextSibling` 出发,只要 `y` 存在且 `y.nodeType != 1`(非元素节点),就持续向 `y.nextSibling` 推进,直到找到真正的元素节点(或到达末尾返回 `null`;实际工程中务必加上 `while (y && y.nodeType != 1)` 的空值保护,防止末尾越界报错)。在现代浏览器中,已可直接用标准元素属性 `firstElementChild`、`lastElementChild`、`nextElementSibling`、`previousElementSibling` 替代手写循环。
以获取首个 `<book>` 的第一个子元素为例:先定义 `get_firstChild(n)`,令 `y = n.firstChild` 并跳过所有非元素节点(`nodeType != 1`);载入 `books.xml` 后对 `xmlDoc.getElementsByTagName("book")[0]` 调用 `get_firstChild(...)`,即可在所有浏览器下稳定输出第一个子元素的节点名 `title`。
更多方向的元素导航模式
同理,可将上述“跳过非元素节点”的封装思路推广至其余三个方向(注意 `lastChild`、`nextSibling`、`previousSibling` 在 DOM 中均为节点属性而非方法):结合 `lastChild` 与向前扫描 `previousSibling` 可定位最后一个子元素(`price`);结合 `nextSibling` 与向前扫描的 `previousSibling` 辅助函数,则可安全获取任意元素紧邻的下一个或上一个同级元素节点。
实测 parentNode 向上导航与跳过空白文本节点的首尾/兄弟元素安全导航
"""Offline XML DOM verification lab for Chapter 13 (nodes-navigate)."""
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>
</bookstore>"""
def get_first_element_child(node):
y = node.firstChild
while y is not None and y.nodeType != 1:
y = y.nextSibling
return y
def get_last_element_child(node):
y = node.lastChild
while y is not None and y.nodeType != 1:
y = y.previousSibling
return y
def get_next_element_sibling(node):
y = node.nextSibling
while y is not None and y.nodeType != 1:
y = y.nextSibling
return y
def get_prev_element_sibling(node):
y = node.previousSibling
while y is not None and y.nodeType != 1:
y = y.previousSibling
return y
def case_navigate_parent_node():
doc = minidom.parseString(BOOKS_XML)
book0 = doc.getElementsByTagName("book")[0]
title0 = doc.getElementsByTagName("title")[0]
expected = {
"book_parent_name": "bookstore",
"title_parent_name": "book",
"root_parent_name": "#document",
}
actual = {
"book_parent_name": book0.parentNode.nodeName,
"title_parent_name": title0.parentNode.nodeName,
"root_parent_name": doc.documentElement.parentNode.nodeName,
}
return {
"name": "navigate_parent_node",
"summary": "通过 parentNode 属性从 book、title 与根元素逐级向上导航并核对父节点名",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_safe_element_first_and_last_child():
doc = minidom.parseString(BOOKS_XML)
book0 = doc.getElementsByTagName("book")[0]
first_el = get_first_element_child(book0)
last_el = get_last_element_child(book0)
expected = {
"raw_first_child_type": 3,
"safe_first_element": "title",
"safe_last_element": "price",
}
actual = {
"raw_first_child_type": book0.firstChild.nodeType,
"safe_first_element": first_el.nodeName,
"safe_last_element": last_el.nodeName,
}
return {
"name": "safe_element_first_and_last_child",
"summary": "使用跳过非元素节点的辅助函数获取第一个子元素(title)与最后一个子元素(price)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_safe_element_next_and_prev_sibling():
doc = minidom.parseString(BOOKS_XML)
book0 = doc.getElementsByTagName("book")[0]
forward = []
cur = get_first_element_child(book0)
while cur is not None:
forward.append(cur.nodeName)
cur = get_next_element_sibling(cur)
backward = []
cur = get_last_element_child(book0)
while cur is not None:
backward.append(cur.nodeName)
cur = get_prev_element_sibling(cur)
expected = {
"forward": ["title", "author", "year", "price"],
"backward": ["price", "year", "author", "title"],
}
actual = {"forward": forward, "backward": backward}
return {
"name": "safe_element_next_and_prev_sibling",
"summary": "验证带空值保护的 nextSibling/previousSibling 元素导航函数在正反向遍历及边界终止处均安全返回",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_lxml_cross_verify_navigation():
root = etree.fromstring(BOOKS_XML.encode("utf-8"))
book0 = root.find("book")
title0 = book0[0]
price0 = book0[-1]
expected = {
"parent": "bookstore",
"first_next": "author",
"last_prev": "year",
}
actual = {
"parent": book0.getparent().tag,
"first_next": title0.getnext().tag,
"last_prev": price0.getprevious().tag,
}
return {
"name": "lxml_cross_verify_navigation",
"summary": "使用 lxml.etree 的 getparent/getnext/getprevious 交叉校验元素导航关系",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_navigate_parent_node(),
case_safe_element_first_and_last_child(),
case_safe_element_next_and_prev_sibling(),
case_lxml_cross_verify_navigation(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 确认 book.parentNode 为 bookstore,安全辅助函数在缩进 books.xml 上精准定位首子元素 title、尾子元素 price 及正反向完整兄弟序列,并与 lxml 核对一致。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
当前源码 SHA256:ce19b1e470d015012cf153ca990633282efa6e7a9cb98d5b8106684718c71f84
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。
ZIP SHA256:ea18243621afc44041345638b66385b73ad57fc39135b04760c5835aeb00784b
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在传统 `get_nextSibling(n)` 辅助函数中,如果写成 `while (y.nodeType != 1)` 而不先判断 `y` 是否为 `null`,对最后一个子元素调用时会发生什么?
展开参考解答
当 `y` 推进到最后一个节点之后变成 `null` 时,读取 `y.nodeType` 会抛出 `TypeError`;因此必须写作 `while (y && y.nodeType != 1)`,或直接改用现代标准的 `n.nextElementSibling`。