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

XML DOM 属性和方法

介绍 XML DOM 面向对象编程接口的属性与方法划分,列举最常用的核心节点属性与方法,并逐段拆解链式读取书名文本的经典语句。

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

学完这一章,你能够

XML DOM 的面向对象编程接口

XML DOM 将整份文档模拟为一组节点对象,并由一套标准化的属性(Properties)和方法(Methods)构成对外编程接口;无论是 JavaScript 还是 Python、Java,都可以依照相同语义操作这些对象。直观来看,属性描述“节点是什么或拥有什么状态”(例如某个节点的名称是 `book`),方法则表示“对节点执行什么动作”(例如向父节点追加或删除一个 `book` 子节点)。

核心 DOM 属性与方法速览

假设 `x` 是一个 DOM 节点对象,最常使用的核心属性包括:`x.nodeName` 返回节点的名称;`x.nodeValue` 返回或设置节点的值;`x.parentNode` 指向 `x` 的父节点;`x.childNodes` 返回 `x` 的子节点列表;`x.attributes` 返回 `x` 的属性节点集合(对非元素节点通常为 `null`/`None`)。

与上述属性配套的核心 DOM 方法(同样以节点对象 `x` 为调用主体)包括:`x.getElementsByTagName(name)` 获取 `x` 子树内所有匹配指定标签名的元素列表;`x.appendChild(node)` 将 `node` 作为最后一个子节点插入 `x`;`x.removeChild(node)` 从 `x` 中移除指定的子节点 `node`。

链式读取元素文本的经典语句拆解

下面这行经典表达式演示了如何从 `books.xml` 的首个 `<title>` 元素中提取书名:`txt = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue`,执行完毕后 `txt` 的结果为 `"Everyday Italian"`。其四段调用含义依次为:`xmlDoc` 是解析器生成的 XML DOM 文档对象;`getElementsByTagName("title")[0]` 取出文档中第一个 `<title>` 元素节点;`childNodes[0]` 定位到该 `<title>` 元素的第一个子节点(即承载文字的文本节点);`nodeValue` 则读取该文本节点保存的实际字符串。

离线实测核心 DOM 属性、增删查方法及链式读取 title 文本表达式

python · 阅读源码
"""Offline XML DOM verification lab for Chapter 07 (methods)."""
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 case_core_dom_node_properties():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    title0 = doc.getElementsByTagName("title")[0]
    text0 = title0.childNodes[0]
    expected = {
        "book_node_name": "book",
        "book_node_value_is_none": True,
        "book_parent_name": "bookstore",
        "book_attr_category": "cooking",
        "title_child_count": 1,
        "text_node_value": "Everyday Italian",
    }
    actual = {
        "book_node_name": book0.nodeName,
        "book_node_value_is_none": book0.nodeValue is None,
        "book_parent_name": book0.parentNode.nodeName,
        "book_attr_category": book0.attributes.getNamedItem("category").nodeValue,
        "title_child_count": len(title0.childNodes),
        "text_node_value": text0.nodeValue,
    }
    return {
        "name": "core_dom_node_properties",
        "summary": "验证典型 DOM 属性 nodeName、nodeValue、parentNode、childNodes 与 attributes 的取值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_core_dom_node_methods():
    doc = minidom.parseString(BOOKS_XML)
    root = doc.documentElement
    initial_count = len(doc.getElementsByTagName("book"))
    new_book = doc.createElement("book")
    new_title = doc.createElement("title")
    new_title.appendChild(doc.createTextNode("DOM Guide"))
    new_book.appendChild(new_title)
    root.appendChild(new_book)
    after_append = len(doc.getElementsByTagName("book"))
    root.removeChild(new_book)
    after_remove = len(doc.getElementsByTagName("book"))
    expected = {"initial_count": 2, "after_append": 3, "after_remove": 2}
    actual = {"initial_count": initial_count, "after_append": after_append, "after_remove": after_remove}
    return {
        "name": "core_dom_node_methods",
        "summary": "验证典型 DOM 方法 getElementsByTagName、appendChild 与 removeChild 的执行效果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_chained_title_text_lookup():
    doc = minidom.parseString(BOOKS_XML)
    txt = doc.getElementsByTagName("title")[0].childNodes[0].nodeValue
    expected = {"txt": "Everyday Italian"}
    actual = {"txt": txt}
    return {
        "name": "chained_title_text_lookup",
        "summary": "执行链式调用 getElementsByTagName('title')[0].childNodes[0].nodeValue 取得首本书名",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lxml_verify_mutation_roundtrip():
    doc = minidom.parseString(BOOKS_XML)
    book0 = doc.getElementsByTagName("book")[0]
    edition = doc.createElement("edition")
    edition.appendChild(doc.createTextNode("1st"))
    book0.appendChild(edition)
    lxml_root = etree.fromstring(doc.toxml().encode("utf-8"))
    expected = {"edition_text": "1st", "book_count": 2}
    actual = {
        "edition_text": lxml_root.findtext("book[1]/edition"),
        "book_count": len(lxml_root.findall("book")),
    }
    return {
        "name": "lxml_verify_mutation_roundtrip",
        "summary": "将 appendChild 修改后的文档序列化并交由 lxml.etree 交叉核对子节点结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_core_dom_node_properties(),
        case_core_dom_node_methods(),
        case_chained_title_text_lookup(),
        case_lxml_verify_mutation_roundtrip(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 确认 nodeName/nodeValue/parentNode/childNodes/attributes 取值准确,getElementsByTagName/appendChild/removeChild 生效,链式读取得到 'Everyday Italian'。
离线实测核心 DOM 属性、增删查方法及链式读取 title 文本表达式

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

当前源码 SHA256:1e145a517188c97c4106f1a29377b4404c3f2c86f2fd12d1404152e8c1530f62

下载本站示例源码

本地运行

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

下载XML DOM 属性和方法实验

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

ZIP SHA256:1d6fee8e7b51d1dccb212a67ec679aea80d0ac1350775d9dfef04276e03a9724

常见错误与边界

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

练习与解答

在表达式 `xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue` 中,去掉 `.childNodes[0]` 会得到什么结果?

展开参考解答

去掉 `.childNodes[0]` 后访问的是 `<title>` 元素节点本身的 `nodeValue`,按 W3C DOM 规范其返回值为 `null`(Python 中为 `None`),无法取得标题文字。

规范与官方依据