蓝色天空网mbsky.com · 知识 · 实践 · 创造XML DOM · 本地阅读预览
教程 / XML / Web Service / XML DOM

XML DOM 访问节点

系统讲解访问 XML DOM 节点的三种核心方式:按标签名检索(getElementsByTagName 与 NodeList 索引/长度遍历)、按 nodeType 遍历子节点列表,以及借助 firstChild 与 nextSibling 沿节点关系导航。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

访问节点的三种核心途径与实例概览

借助 XML DOM,程序能够定位并访问文档中的任意节点。围绕 `books.xml`(在浏览器示例中通常配合外部 `loadXMLDoc()` 加载),常见操作涵盖五类基础场景:按节点列表索引取出第三个 `<title>` 元素;借助 `length` 属性遍历全部 `<title>`;查看根元素的 `nodeType`;基于 `nodeType` 遍历根元素下的元素子节点;以及结合 `nodeType` 与 `nextSibling` 沿同级关系遍历元素。

归纳而言,在 XML DOM 中访问节点主要有三条路径:一是通过 `getElementsByTagName()` 按标签名直接检索;二是通过循环遍历节点树中的子节点集合;三是利用父子与兄弟关系属性在节点树中进行导航。

使用 getElementsByTagName() 与 NodeList 索引遍历

`node.getElementsByTagName("tagname")` 会返回指定节点下所有匹配标签名的后代元素。若在某个局部元素 `x` 上调用 `x.getElementsByTagName("title")`,搜索范围仅限于 `x` 的子树;若要检索整份 XML 文档中的所有 `<title>`,则应在文档节点本身调用 `xmlDoc.getElementsByTagName("title")`。

`getElementsByTagName()` 的返回值是一个有序节点列表(NodeList,行为类似数组)。将 `books.xml` 载入 `xmlDoc` 并令 `x = xmlDoc.getElementsByTagName("title")` 后,即可按从 `0` 开始的下标访问具体元素——例如 `y = x[2]` 会取得文档中的第三个 `<title>`(`"XQuery Kick Start"`)。关于节点列表的更多细节将在后文专章展开。

节点列表的 `length` 属性表示其中包含的节点总数。结合 `for (i = 0; i < x.length; i++)` 循环即可依次读取每个 `<title>` 元素的子文本节点 `x[i].childNodes[0].nodeValue`,将四本书的标题全部输出。

检查 nodeType 并遍历子节点列表

在遍历节点树之前,需掌握三个基础属性:文档的 `documentElement` 指向根元素节点,节点的 `nodeName` 给出节点名称,`nodeType` 则以整数常量标识节点类型(元素节点为 `1`)。下一章将全面介绍各节点信息属性。

当通过 `x = xmlDoc.documentElement.childNodes` 获取根元素的所有子节点时,格式化 XML 中的换行和缩进会混入空白文本节点(`nodeType === 3`)。因此在循环中先判断 `if (x[i].nodeType == 1)`,仅在确认其为元素节点后再输出 `x[i].nodeName`,即可稳定得到四个 `book` 元素名称。

利用 firstChild 与 nextSibling 沿节点关系导航

第三种方式是依赖节点关系指针游走:先获取第一个 `<book>` 的子节点集合 `x`(用来确定迭代次数)并将游标 `y` 初始化为 `firstChild`;在每轮循环中检查 `y.nodeType == 1`,若是元素节点便输出 `y.nodeName`,随后将 `y` 推进至 `y.nextSibling` 继续检查,直至走完所有同级节点,依次输出 `title`、`author`、`year`、`price`。

实测按标签名索引检索、length 遍历、nodeType 过滤与 nextSibling 导航

python · 阅读源码
"""Offline XML DOM verification lab for Chapter 08 (nodes-access)."""
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_get_elements_by_tag_name_scope_and_index():
    doc = minidom.parseString(BOOKS_XML)
    all_titles = doc.getElementsByTagName("title")
    first_book = doc.getElementsByTagName("book")[0]
    scoped_titles = first_book.getElementsByTagName("title")
    third_title = all_titles[2].childNodes[0].nodeValue
    expected = {
        "doc_title_count": 4,
        "scoped_book0_title_count": 1,
        "third_title_index_2": "XQuery Kick Start",
    }
    actual = {
        "doc_title_count": len(all_titles),
        "scoped_book0_title_count": len(scoped_titles),
        "third_title_index_2": third_title,
    }
    return {
        "name": "get_elements_by_tag_name_scope_and_index",
        "summary": "对比文档级与局部元素级 getElementsByTagName 作用域,并按 0 起始索引访问第 3 个 title",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nodelist_length_loop_titles():
    doc = minidom.parseString(BOOKS_XML)
    x = doc.getElementsByTagName("title")
    titles = [x[i].childNodes[0].nodeValue for i in range(x.length)]
    lxml_titles = [el.text for el in etree.fromstring(BOOKS_XML.encode("utf-8")).findall(".//title")]
    expected = {
        "length": 4,
        "titles": ["Everyday Italian", "Harry Potter", "XQuery Kick Start", "Learning XML"],
        "matches_lxml": True,
    }
    actual = {
        "length": x.length,
        "titles": titles,
        "matches_lxml": titles == lxml_titles,
    }
    return {
        "name": "nodelist_length_loop_titles",
        "summary": "使用节点列表的 length 属性循环输出全部 title 文本值,并用 lxml 核对一致",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_root_node_type_and_childnodes_loop():
    doc = minidom.parseString(BOOKS_XML)
    root = doc.documentElement
    element_children = [
        node.nodeName for node in root.childNodes if node.nodeType == 1
    ]
    expected = {
        "root_name": "bookstore",
        "root_type": 1,
        "raw_child_count": 9,
        "element_child_names": ["book", "book", "book", "book"],
    }
    actual = {
        "root_name": root.nodeName,
        "root_type": root.nodeType,
        "raw_child_count": len(root.childNodes),
        "element_child_names": element_children,
    }
    return {
        "name": "root_node_type_and_childnodes_loop",
        "summary": "检查 documentElement 的 nodeName/nodeType,并遍历其 childNodes 过滤出 nodeType==1 的元素节点",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sibling_navigation_with_nextsibling():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    names = []
    y = book0.firstChild
    for _ in range(len(book0.childNodes)):
        if y.nodeType == 1:
            names.append(y.nodeName)
        y = y.nextSibling
    expected = {
        "element_names": ["title", "author", "year", "price"],
        "ended_at_none": True,
    }
    actual = {
        "element_names": names,
        "ended_at_none": y is None,
    }
    return {
        "name": "sibling_navigation_with_nextsibling",
        "summary": "从第一个 book 的 firstChild 起沿 nextSibling 导航并按 nodeType==1 筛选子元素名",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_get_elements_by_tag_name_scope_and_index(),
        case_nodelist_length_loop_titles(),
        case_root_node_type_and_childnodes_loop(),
        case_sibling_navigation_with_nextsibling(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 确认全局/局部 getElementsByTagName 作用域正确、x[2] 为 XQuery Kick Start、length 循环输出全部 4 书名,且 nodeType==1 过滤与 nextSibling 导航结果一致。
实测按标签名索引检索、length 遍历、nodeType 过滤与 nextSibling 导航

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

当前源码 SHA256:3fd74381fb14f14fe53798080a5a9f363568714017725db35da973c5eab5181f

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载XML DOM 访问节点实验

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

ZIP SHA256:b7b1aadd9261f9e1b8de966084e33ff61901c36cb521d76b8ef3f310f97f7b03

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在循环遍历 `xmlDoc.documentElement.childNodes` 时,为什么要额外判断 `x[i].nodeType == 1`?

展开参考解答

因为格式化 XML 的换行与缩进会产生 `nodeType == 3` 的空白文本节点(此外还可能包含注释节点 `8`),只有 `nodeType == 1` 才表示元素节点。

规范与官方依据