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

XML DOM 获取节点值

系统演示通过 childNodes[0].nodeValue 获取元素文本值,以及通过 getAttribute() 与 getAttributeNode().nodeValue 两种方式读取 XML 属性值,并核对缺失属性边界行为。

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

学完这一章,你能够

获取元素文本值:定位子文本节点

读取 XML 文档数据时,最核心的两个接口是读取文本值的 `nodeValue` 属性和读取属性值的 `getAttribute()` 方法。由于元素节点自身并不存储文字内容,其文本总是存放在它的子文本节点中,因此“获取元素的值”实质上是先取出该元素下的文本子节点,再读取该文本节点的 `nodeValue`。

分步来看:`getElementsByTagName("title")` 按源文档顺序返回所有 `<title>` 元素组成的节点列表,先取首个元素 `x = xmlDoc.getElementsByTagName("title")[0]`;由于 `<title>` 仅包含一个文本子节点,再通过 `y = x.childNodes[0]` 拿到该文本节点;最后读取 `txt = y.nodeValue`,即可获得结果 `"Everyday Italian"`。将上述步骤放入循环,便可依次提取文档中全部 `<title>` 元素的书名。

获取属性值:getAttribute() 与 getAttributeNode()

与元素节点不同,属性节点在 DOM 中直接持有文本值(即属性本身的字符串值)。读取元素属性值有两种标准方式:直接调用元素的 `getAttribute()` 方法,或者先获取属性节点对象再读取其 `nodeValue`。

使用 `getAttribute(name)` 最为简洁:加载 `books.xml` 后执行 `txt = xmlDoc.getElementsByTagName("title")[0].getAttribute("lang")`,即可直接返回字符串 `"en"`;遍历全部 `<book>` 元素并调用 `getAttribute("category")` 则可提取所有分类。需注意不同实现对缺失属性的返回值差异:W3C 浏览器 DOM 返回 `null`,而 Python `xml.dom.minidom` 返回空字符串 `""`,不确定属性是否存在时可先用 `hasAttribute()` 检查。

如果需要获得完整的属性节点对象(`Attr`,`nodeType === 2`),可调用 `getAttributeNode(name)`:先令 `x = xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang")`,再通过 `txt = x.nodeValue` 同样得到 `"en"`。遍历全部 `<book>` 并调用 `getAttributeNode("category").nodeValue` 也能取得每本书的分类值,且在属性不存在时该方法在浏览器与 Python `minidom` 中均一致返回空对象(`null` / `None`)。

实测分步读取元素文本值、getAttribute 与 getAttributeNode 及缺失属性边界

python · 阅读源码
"""Offline XML DOM verification lab for Chapter 14 (nodes-get)."""
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_get_first_title_text_node_value():
    doc = minidom.parseString(BOOKS_XML)
    x = doc.getElementsByTagName("title")[0]
    y = x.childNodes[0]
    txt = y.nodeValue
    all_titles = [el.childNodes[0].nodeValue for el in doc.getElementsByTagName("title")]
    expected = {
        "first_title": "Everyday Italian",
        "title_child_count": 1,
        "all_titles": ["Everyday Italian", "Harry Potter", "XQuery Kick Start", "Learning XML"],
    }
    actual = {
        "first_title": txt,
        "title_child_count": len(x.childNodes),
        "all_titles": all_titles,
    }
    return {
        "name": "get_first_title_text_node_value",
        "summary": "分步通过 getElementsByTagName、childNodes[0] 与 nodeValue 读取首个及全部 title 文本值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_get_attribute_method():
    doc = minidom.parseString(BOOKS_XML)
    first_lang = doc.getElementsByTagName("title")[0].getAttribute("lang")
    categories = [b.getAttribute("category") for b in doc.getElementsByTagName("book")]
    lxml_cats = [b.get("category") for b in etree.fromstring(BOOKS_XML.encode("utf-8")).findall("book")]
    expected = {
        "first_title_lang": "en",
        "book_categories": ["cooking", "children", "web", "web"],
        "matches_lxml": True,
    }
    actual = {
        "first_title_lang": first_lang,
        "book_categories": categories,
        "matches_lxml": categories == lxml_cats,
    }
    return {
        "name": "get_attribute_method",
        "summary": "使用 getAttribute() 获取首书 title 的 lang 属性及全部 book 的 category 属性,并用 lxml 核对",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_get_attribute_node_method():
    doc = minidom.parseString(BOOKS_XML)
    lang_node = doc.getElementsByTagName("title")[0].getAttributeNode("lang")
    cat_values = [b.getAttributeNode("category").nodeValue for b in doc.getElementsByTagName("book")]
    expected = {
        "node_type": 2,
        "node_name": "lang",
        "node_value": "en",
        "all_categories": ["cooking", "children", "web", "web"],
    }
    actual = {
        "node_type": lang_node.nodeType,
        "node_name": lang_node.nodeName,
        "node_value": lang_node.nodeValue,
        "all_categories": cat_values,
    }
    return {
        "name": "get_attribute_node_method",
        "summary": "使用 getAttributeNode() 返回属性节点对象并读取其 nodeName/nodeType/nodeValue",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_missing_attribute_boundary_behavior():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    expected = {
        "has_cover": False,
        "minidom_get_attribute_missing": "",
        "get_attribute_node_missing_is_none": True,
    }
    actual = {
        "has_cover": book0.hasAttribute("cover"),
        "minidom_get_attribute_missing": book0.getAttribute("cover"),
        "get_attribute_node_missing_is_none": book0.getAttributeNode("cover") is None,
    }
    return {
        "name": "missing_attribute_boundary_behavior",
        "summary": "验证缺失属性时 hasAttribute、getAttribute 与 getAttributeNode 的边界返回结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_get_first_title_text_node_value(),
        case_get_attribute_method(),
        case_get_attribute_node_method(),
        case_missing_attribute_boundary_behavior(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 确认首书 title 文本为 Everyday Italian、lang 为 en,全部 book category 为 cooking/children/web/web,缺失属性 getAttributeNode 返回 None。
实测分步读取元素文本值、getAttribute 与 getAttributeNode 及缺失属性边界

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

当前源码 SHA256:1dd3167256bafcca07508ac543f27f5efbd12c8d550252f34d6cc1444fcfa150

下载本站示例源码

本地运行

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

下载XML DOM 获取节点值实验

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

ZIP SHA256:b5b9462f2d25755748554584df311698d3428ba3ede0210dac849c9f4fbd0ad2

常见错误与边界

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

练习与解答

`element.getAttribute("lang")` 与 `element.getAttributeNode("lang")` 的返回值类型有何不同?

展开参考解答

`getAttribute()` 直接返回属性值的字符串(如 `"en"`);`getAttributeNode()` 返回的是代表该属性的 `Attr` 节点对象(`nodeType === 2`),需进一步访问其 `.nodeValue` 或 `.value` 才能取得字符串。

规范与官方依据