DOM Attribute
详解 XML DOM 中 Attr 属性节点的模型定位、与父节点及 childNodes 的独立关系,以及 15 项核心属性(含 ownerElement、specified、isId、namespaceURI 与 value)参考。
学完这一章,你能够
- 详解 XML DOM 中 Attr 属性节点的模型定位、与父节点及 childNodes 的独立关系,以及 15 项核心属性(含 ownerElement、specified、isId、namespaceURI 与 value)参考。
Attr 对象模型与非子节点特征
`Attr` 对象表示附属在 `Element` 元素节点上的单个 XML 属性(`nodeType === 2`),属性的合法取值集合或默认值通常在关联的 DTD 或 XML Schema 中定义。
尽管在 W3C DOM 规范中 `Attr` 继承自 `Node`(因此在需要时仍可访问 `nodeName`、`nodeValue` 等通用成员),但属性在文档树中**不拥有父节点**,也不被视作所属元素的子节点(不会出现在 `element.childNodes` 中)。因此 `attr.parentNode`、`attr.previousSibling`、`attr.nextSibling` 等树指针均返回 `null`,需改用 `attr.ownerElement` 来获取属性所依附的 `Element` 对象。
Attr 对象属性参考
下表整理了 `Attr` 对象的 15 项常用属性。日常开发最常使用 `name`、`value`、`ownerElement`、`namespaceURI`、`prefix` 与 `localName`;而 `specified`(在现代 DOM Living Standard 中已固定返回 `true`,且在 CPython `minidom` 默解析器下需结合 DTD 解析器区分默认值)与 `isId`、`schemaTypeInfo` 则多见于带 DTD/Schema 校验的 XML 处理场景。
Attr 对象属性参考
| 属性 | 读写性与作用说明 |
| baseURI | 只读;返回属性所属上下文的绝对基准 URI。 |
| isId | 历史 DOM Level 3 只读布尔值:若该属性被 DTD/Schema 或 `setIdAttribute*` 声明为 ID 类型则返回 `true`,否则返回 `false`。 |
| localName | 只读;返回带命名空间属性名称去除前缀后的本地部分。 |
| name | 只读;返回属性的完整限定名称(与 `nodeName` 一致)。 |
| namespaceURI | 只读;返回属性的命名空间 URI,未绑定命名空间时为 `null`。 |
| nodeName | 只读;对 `Attr` 节点恒返回属性名称。 |
| nodeType | 只读;对 `Attr` 节点恒返回 `2`(`Node.ATTRIBUTE_NODE`)。 |
| nodeValue | 读写;读取或修改属性值字符串(与 `value` 保持同步)。 |
| ownerDocument | 只读;返回该属性所属的顶层 `Document` 文档对象。 |
| ownerElement | 只读;返回该属性所附属的 `Element` 元素节点,游离属性返回 `null`。 |
| prefix | 设置或返回属性的命名空间前缀(现代规范中只读)。 |
| schemaTypeInfo | 历史 DOM Level 3 只读属性:返回与属性关联的 DTD/Schema 类型信息对象。 |
| specified | 只读布尔值:规范定义为属性值显式写在文档中时为 `true`,来自 DTD/Schema 默认值时为 `false`(现代 DOM 已固定返回 `true`)。 |
| textContent | 读写;对 `Attr` 节点等价于读取或设置其属性值文本。 |
| value | 读写;设置或返回属性的字符串值,修改后同步反映到所属元素。 |
离线验证 Attr 归属关系、命名空间属性变更、DTD 默认值与 ID 属性判定
展开查看收起
"""Offline XML DOM verification lab for Chapter 31 (attribute)."""
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/lib/" xmlns:pub="urn:pub" category="web" pub:isbn="978-0-123456-47-2"><title>XML DOM</title></book>'
def case_attr_core_and_owner_properties():
doc = minidom.parseString(BOOK_XML)
book = doc.documentElement
attr = book.getAttributeNode("category")
expected = {
"name": "category",
"value": "web",
"nodeName": "category",
"nodeValue": "web",
"nodeType": 2,
"ownerElement_is_book": True,
"ownerDocument_is_doc": True,
"parentNode_is_none": True,
"not_in_childNodes": True,
}
actual = {
"name": attr.name,
"value": attr.value,
"nodeName": attr.nodeName,
"nodeValue": attr.nodeValue,
"nodeType": attr.nodeType,
"ownerElement_is_book": attr.ownerElement is book,
"ownerDocument_is_doc": attr.ownerDocument is doc,
"parentNode_is_none": attr.parentNode is None,
"not_in_childNodes": all(c.nodeType != Node.ATTRIBUTE_NODE for c in book.childNodes),
}
return {
"name": "attr_core_and_owner_properties",
"summary": "验证 Attr 节点核心属性、ownerElement/ownerDocument 归属及属性非元素子节点的规范特征",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_attr_namespace_and_value_mutation():
doc = minidom.parseString(BOOK_XML)
book = doc.documentElement
ns_attr = book.getAttributeNodeNS("urn:pub", "isbn")
before_val = ns_attr.value
ns_attr.value = "978-0-999999-00-1"
expected = {
"namespaceURI": "urn:pub",
"prefix": "pub",
"localName": "isbn",
"before_val": "978-0-123456-47-2",
"after_value": "978-0-999999-00-1",
"after_nodeValue": "978-0-999999-00-1",
"reflected_on_element": "978-0-999999-00-1",
}
actual = {
"namespaceURI": ns_attr.namespaceURI,
"prefix": ns_attr.prefix,
"localName": ns_attr.localName,
"before_val": before_val,
"after_value": ns_attr.value,
"after_nodeValue": ns_attr.nodeValue,
"reflected_on_element": book.getAttributeNS("urn:pub", "isbn"),
}
return {
"name": "attr_namespace_and_value_mutation",
"summary": "验证带命名空间 Attr 的 namespaceURI/prefix/localName 及修改 value 同步更新 nodeValue 与元素属性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_attr_specified_isid_and_schema_info():
doc = minidom.parseString(BOOK_XML)
book = doc.documentElement
cat = book.getAttributeNode("category")
before_is_id = cat.isId
book.setIdAttributeNode(cat)
after_is_id = cat.isId
# Observe DTD default attribute injection vs explicit document attribute via lxml.etree
dtd_xml = b"""<!DOCTYPE item [
<!ELEMENT item EMPTY>
<!ATTLIST item status CDATA "draft" code CDATA #REQUIRED>
]><item code="X1"/>"""
dtd_root = etree.fromstring(dtd_xml, parser=etree.XMLParser(load_dtd=True, attribute_defaults=True))
explicit_in_source = "code" in dtd_root.attrib and 'status=' not in dtd_xml.decode("utf-8")
default_from_dtd = dtd_root.attrib.get("status") == "draft"
lroot = etree.fromstring(BOOK_XML.encode("utf-8"))
expected = {
"has_specified_attr_on_minidom": True,
"explicit_code_vs_dtd_default_status": True,
"before_isId": False,
"after_isId": True,
"lookup_by_id_matches_book": True,
"owner_baseURI": "https://example.org/lib/",
"schemaTypeInfo_without_xsd_is_none": True,
}
actual = {
"has_specified_attr_on_minidom": isinstance(cat.specified, bool),
"explicit_code_vs_dtd_default_status": explicit_in_source and default_from_dtd,
"before_isId": before_is_id,
"after_isId": after_is_id,
"lookup_by_id_matches_book": doc.getElementById("web") is book,
"owner_baseURI": lroot.base,
"schemaTypeInfo_without_xsd_is_none": getattr(cat, "schemaType", None) in (None, (None, None)) or getattr(cat.schemaType, "name", None) is None,
}
return {
"name": "attr_specified_isid_and_schema_info",
"summary": "验证 Attr.specified、setIdAttributeNode 切换 isId、baseURI 继承与无模式校验时的 schemaTypeInfo",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_attr_core_and_owner_properties(),
case_attr_namespace_and_value_mutation(),
case_attr_specified_isid_and_schema_info(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为按照 W3C DOM 规范,属性不属于元素的子节点树,`attr.parentNode` 永远为 `null`;要获取属性依附的元素节点,必须访问 `attr.ownerElement`。