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

DOM Element

系统梳理 XML DOM 中最常用的 Element 元素节点接口、文本存于子文本节点的易错要点,以及 17 项核心属性与 36 项属性管理、子树查询和节点操作方法。

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

学完这一章,你能够

Element 对象与“文本存于文本节点”原则

`Element` 对象代表 XML 文档中的一个标签元素(`nodeType === 1`),它既可以挂载属性,也可以嵌套其他子元素或文本内容。

开发 XML DOM 时最容易踩中的误区是以为元素节点本身直接保存着文本。事实上,文本永远存储在元素下属的 `Text` 子节点中:即便是最简单的 `<year>2005</year>`,在 DOM 树里也由一个名为 `year` 的 `Element` 节点和一个包含 `"2005"` 的子 `Text` 节点组成,直接读取 `yearElement.nodeValue` 只会得到 `null`。

由于 `Element` 直接继承自 `Node`,因此它完整拥有 `Node` 的父子同级导航与子树增删能力,同时额外扩展了属性读写、按标签名查询后代以及 ID 属性登记等元素专属方法。

Element 对象属性与方法参考

以下两张参考表逐项收录了 `Element` 的 17 项属性与 36 项方法。其中普通与带命名空间的属性方法(`getAttribute*`/`setAttribute*`/`hasAttribute*`/`removeAttribute*` 及 `*Node` 变体)和后代查询方法(`getElementsByTagName*`)在 XML 处理中最高频;而 `schemaTypeInfo`、`getFeature()`、`getUserData()`、`setUserData()`、`isSupported()` 与 `setIdAttribute*()` 属于 W3C DOM Level 3 扩展,在 Python `minidom` 等 XML DOM 库中部分保留,在现代浏览器 DOM Living Standard 中多已精简或废弃。

Element 对象属性参考

属性作用说明
attributes只读;返回包含该元素全部属性节点的动态 `NamedNodeMap`。
baseURI只读;返回元素的绝对基准 URI(受祖先或自身 `xml:base` 影响)。
childNodes只读;返回元素所有直接子节点的 `NodeList`(含文本、注释与子元素)。
firstChild只读;返回元素的第一个子节点,无子节点时为 `null`。
lastChild只读;返回元素的最后一个子节点,无子节点时为 `null`。
localName只读;返回元素限定名去掉命名空间前缀后的本地名称。
namespaceURI只读;返回元素绑定的命名空间 URI,未绑定时为 `null`。
nextSibling只读;返回紧跟在该元素之后的同级节点。
nodeName只读;对元素节点返回与 `tagName` 相同的元素名称。
nodeType只读;对元素节点恒返回 `1`(`Node.ELEMENT_NODE`)。
ownerDocument只读;返回该元素所属的顶层 `Document` 文档对象。
parentNode只读;返回该元素的父节点(根元素的父节点为 `Document`)。
prefix设置或返回元素的命名空间前缀(无前缀时为 `null`)。
previousSibling只读;返回紧邻在该元素之前的同级节点。
schemaTypeInfo历史 DOM Level 3 只读属性:返回经 DTD/XML Schema 校验后关联的类型信息对象。
tagName只读;返回元素的限定标签名称(XML 中严格区分大小写)。
textContent读写;读取或整体替换该元素及其全部后代节点的纯文本内容。

Element 对象方法参考

方法功能说明
appendChild(newChild)将新节点添加到元素子节点列表末尾并返回该节点。
cloneNode(deep)克隆元素及其属性;`deep=true` 同时深度克隆所有后代子节点。
compareDocumentPosition(other)返回位掩码,比较当前元素与另一节点在文档树中的相对位置。
getAttribute(name)按属性名返回属性值字符串;属性不存在时返回空字符串或 `null`(依具体实现)。
getAttributeNS(namespaceURI, localName)按命名空间 URI 与本地名返回属性值字符串。
getAttributeNode(name)按属性名返回对应的 `Attr` 属性节点对象,不存在时为 `null`。
getAttributeNodeNS(namespaceURI, localName)按命名空间 URI 与本地名返回对应的 `Attr` 属性节点对象。
getElementsByTagName(name)返回当前元素子树内所有匹配标签名的后代元素 `NodeList`。
getElementsByTagNameNS(namespaceURI, localName)返回当前元素子树内匹配命名空间 URI 与本地名的后代元素 `NodeList`。
getFeature(feature, version)历史 DOM Level 3 方法:返回实现指定特性和版本的专门接口对象。
getUserData(key)历史 DOM Level 3 方法:读取先前通过 `setUserData()` 关联到元素键上的自定义对象。
hasAttribute(name)若元素存在指定名称的属性返回 `true`,否则返回 `false`。
hasAttributeNS(namespaceURI, localName)若元素存在匹配命名空间 URI 与本地名的属性返回 `true`,否则返回 `false`。
hasAttributes()若元素拥有至少一个属性返回 `true`,否则返回 `false`。
hasChildNodes()若元素包含至少一个子节点返回 `true`,否则返回 `false`。
insertBefore(newNode, refNode)在指定已有子节点之前插入新的子节点。
isDefaultNamespace(namespaceURI)检查指定 URI 是否为当前元素作用域的默认命名空间。
isEqualNode(other)深度比较两个元素及其属性和后代结构是否等价。
isSameNode(other)检查两个引用是否指向同一个元素对象实例。
isSupported(feature, version)历史 DOM Level 2/3 方法:检查该元素实现是否支持指定特性与版本。
lookupNamespaceURI(prefix)查找当前元素作用域中与指定前缀绑定的命名空间 URI。
lookupPrefix(namespaceURI)查找当前元素作用域中与指定命名空间 URI 对应的前缀。
normalize()规范化子树中的所有 `Text` 节点,合并相邻文本节点并清理空文本节点。
removeAttribute(name)按属性名删除元素上的指定属性。
removeAttributeNS(namespaceURI, localName)按命名空间 URI 与本地名删除元素上的指定属性。
removeAttributeNode(attrNode)移除并返回指定的 `Attr` 属性节点对象。
removeChild(oldChild)从元素的子节点列表中移除指定子节点并返回它。
replaceChild(newChild, oldChild)用新节点替换指定旧子节点,并返回被替换的旧节点。
setUserData(key, data, handler)历史 DOM Level 3 方法:把自定义对象关联到元素的指定键上。
setAttribute(name, value)添加新属性或覆盖已有同名属性的值。
setAttributeNS(namespaceURI, qualifiedName, value)添加或更新带命名空间 URI 与限定名的属性。
setAttributeNode(attrNode)将 `Attr` 属性节点绑定到元素上;若替换了已有同名属性则返回旧节点。
setAttributeNodeNS(attrNode)将带命名空间的 `Attr` 属性节点绑定到元素上。
setIdAttribute(name, isId)将指定名称的属性声明(或取消声明)为用户确定的 ID 属性,使其可被 `document.getElementById()` 检索。
setIdAttributeNS(namespaceURI, localName, isId)将指定命名空间 URI 与本地名的属性声明为用户确定的 ID 属性。
setIdAttributeNode(idAttr, isId)将指定的 `Attr` 节点对象声明为用户确定的 ID 属性。

离线验证 Element 文本子节点原则、普通/命名空间属性 CRUD、子树操作与 ID 属性注册

python · 阅读源码
"""Offline XML DOM verification lab for Chapter 30 (element)."""
import json
from xml.dom import Node, minidom
from lxml import etree

VERSION = "CPython 3.12.14 offline XML DOM verifier (xml.dom.minidom + lxml.etree)"

BOOK_XML = """<book xml:base="https://example.org/books/" xmlns="urn:books" xmlns:ed="urn:edition" id="b1" ed:code="E9">
  <title>XML DOM</title><year>2005</year>
</book>"""


def elem_text_content(node) -> str:
    parts = []
    for c in node.childNodes:
        if c.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
            parts.append(c.data)
        elif c.nodeType == Node.ELEMENT_NODE:
            parts.append(elem_text_content(c))
    return "".join(parts)


def case_element_text_child_and_node_props():
    doc = minidom.parseString("<book><title>XML DOM</title><year>2005</year></book>")
    book = doc.documentElement
    title = book.firstChild
    year = book.lastChild

    expected = {
        "year_tagName": "year",
        "year_nodeName": "year",
        "year_nodeType": 1,
        "year_nodeValue_is_none": True,
        "year_firstChild_type": 3,
        "year_firstChild_value": "2005",
        "year_parent_tag": "book",
        "year_prev_tag": "title",
        "title_next_tag": "year",
        "year_owner_is_doc": True,
        "book_textContent": "XML DOM2005",
    }
    actual = {
        "year_tagName": year.tagName,
        "year_nodeName": year.nodeName,
        "year_nodeType": year.nodeType,
        "year_nodeValue_is_none": year.nodeValue is None,
        "year_firstChild_type": year.firstChild.nodeType,
        "year_firstChild_value": year.firstChild.nodeValue,
        "year_parent_tag": year.parentNode.tagName,
        "year_prev_tag": year.previousSibling.tagName,
        "title_next_tag": title.nextSibling.tagName,
        "year_owner_is_doc": year.ownerDocument is doc,
        "book_textContent": elem_text_content(book),
    }
    return {
        "name": "element_text_child_and_node_props",
        "summary": "验证 <year>2005</year> 文本存储在子文本节点中,以及 Element 继承自 Node 的核心导航属性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_element_attribute_crud_and_ns():
    doc = minidom.parseString(BOOK_XML)
    book = doc.documentElement

    book.setAttribute("category", "tech")
    has_cat = book.hasAttribute("category")
    cat_val = book.getAttribute("category")
    cat_node = book.getAttributeNode("category")

    a_node = doc.createAttribute("edition")
    a_node.value = "3rd"
    book.setAttributeNode(a_node)
    removed_node = book.removeAttributeNode(a_node)

    book.setAttributeNS("urn:edition", "ed:status", "published")
    ns_val = book.getAttributeNS("urn:edition", "status")
    has_ns = book.hasAttributeNS("urn:edition", "status")
    ns_node = book.getAttributeNodeNS("urn:edition", "status")

    a_ns = doc.createAttributeNS("urn:edition", "ed:region")
    a_ns.value = "APAC"
    book.setAttributeNodeNS(a_ns)
    book.removeAttributeNS("urn:edition", "region")
    book.removeAttribute("category")

    expected = {
        "hasAttributes_initial": True,
        "has_cat": True,
        "cat_val": "tech",
        "cat_node_name": "category",
        "removed_node_value": "3rd",
        "ns_val": "published",
        "has_ns": True,
        "ns_node_localName": "status",
        "region_removed": True,
        "cat_removed": True,
    }
    actual = {
        "hasAttributes_initial": book.hasAttributes(),
        "has_cat": has_cat,
        "cat_val": cat_val,
        "cat_node_name": cat_node.name,
        "removed_node_value": removed_node.value,
        "ns_val": ns_val,
        "has_ns": has_ns,
        "ns_node_localName": ns_node.localName,
        "region_removed": not book.hasAttributeNS("urn:edition", "region"),
        "cat_removed": not book.hasAttribute("category"),
    }
    return {
        "name": "element_attribute_crud_and_ns",
        "summary": "验证 Element 全套普通属性与命名空间属性读写、节点操作及删除方法",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_element_descendant_query_and_mutation():
    doc = minidom.parseString(
        '<shelf xmlns:bk="urn:books"><bk:item>A</bk:item><item>B</item></shelf>'
    )
    shelf = doc.documentElement
    c = doc.createElement("item")
    c.appendChild(doc.createTextNode("C1"))
    c.appendChild(doc.createTextNode("C2"))
    shelf.appendChild(c)
    c.normalize()

    d = doc.createElement("item")
    d.appendChild(doc.createTextNode("D"))
    shelf.insertBefore(d, c)

    e = doc.createElement("item")
    e.appendChild(doc.createTextNode("E"))
    shelf.replaceChild(e, d)
    shelf.removeChild(e)
    c_copy = c.cloneNode(True)
    shelf.appendChild(c_copy)

    plain_items = shelf.getElementsByTagName("item")
    ns_items = shelf.getElementsByTagNameNS("urn:books", "item")

    expected = {
        "has_children": True,
        "normalized_c_text": "C1C2",
        "plain_item_texts": ["B", "C1C2", "C1C2"],
        "ns_item_texts": ["A"],
    }
    actual = {
        "has_children": shelf.hasChildNodes(),
        "normalized_c_text": c.firstChild.data,
        "plain_item_texts": [el.firstChild.data for el in plain_items],
        "ns_item_texts": [el.firstChild.data for el in ns_items],
    }
    return {
        "name": "element_descendant_query_and_mutation",
        "summary": "验证 Element 子树查询(TagName/TagNameNS)、增删改克隆与 normalize() 合并相邻文本节点",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_element_id_namespace_and_dom3_methods():
    doc = minidom.parseString(BOOK_XML)
    book = doc.documentElement
    book.setIdAttribute("id")
    book.setIdAttributeNS("urn:edition", "code")
    custom_id = doc.createAttribute("uid")
    custom_id.value = "U100"
    book.setAttributeNode(custom_id)
    book.setIdAttributeNode(custom_id)

    lroot = etree.fromstring(BOOK_XML.encode("utf-8"))
    nsmap = lroot.nsmap

    expected = {
        "get_by_id": True,
        "get_by_ns_id": True,
        "get_by_attr_node_id": True,
        "localName": "book",
        "namespaceURI": "urn:books",
        "prefix_is_none": True,
        "baseURI": "https://example.org/books/",
        "lookup_ed_ns": "urn:edition",
        "isSameNode_self": True,
        "isSupported_xml": True,
    }
    actual = {
        "get_by_id": doc.getElementById("b1") is book,
        "get_by_ns_id": doc.getElementById("E9") is book,
        "get_by_attr_node_id": doc.getElementById("U100") is book,
        "localName": book.localName,
        "namespaceURI": book.namespaceURI,
        "prefix_is_none": book.prefix is None,
        "baseURI": lroot.base,
        "lookup_ed_ns": nsmap.get("ed"),
        "isSameNode_self": book.isSameNode(book),
        "isSupported_xml": doc.implementation.hasFeature("XML", "1.0"),
    }
    return {
        "name": "element_id_namespace_and_dom3_methods",
        "summary": "验证 setIdAttribute 系列方法、命名空间属性、baseURI 与 DOM Level 3 扩展接口语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_element_text_child_and_node_props(),
        case_element_attribute_crud_and_ns(),
        case_element_descendant_query_and_mutation(),
        case_element_id_namespace_and_dom3_methods(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器通过全部 4 项用例:核实 <year>2005</year> 文本位于 firstChild、完整覆盖 12 项属性方法、验证子树增删改与 normalize(),以及 setIdAttribute 系列与 getElementById 联动。
离线验证 Element 文本子节点原则、普通/命名空间属性 CRUD、子树操作与 ID 属性注册

所需环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。

当前源码 SHA256:930c5dc5a8a00d43b0461c20b012390d5ea271dec5af225a575d66ad0b7efbda

下载本站示例源码

本地运行

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

下载DOM Element实验

所需环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。

ZIP SHA256:4413f15075be048c6b721411e3aa23f5ef59ab893a8b64fe2386fe213c6c44a7

常见错误与边界

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

练习与解答

在纯 XML 文档中,为什么有时给元素写了 `id="b1"` 却无法通过 `document.getElementById("b1")` 查到,而调用 `setIdAttribute("id")` 后就能查到?

展开参考解答

因为与 HTML 固定把 `id` 视为 ID 属性不同,通用 XML 中解析器默认并不知道哪个属性具有 ID 语义,必须借助 DTD/Schema 的 `ID` 类型声明、`xml:id` 或在代码中显式调用 `setIdAttribute*()` 注册后,`getElementById()` 才会建立索引。

规范与官方依据