xml.dom --- 文档对象模型 API

源代码: Lib/xml/dom/__init__.py


文档对象模型“DOM”是一个来自万维网联盟(W3C)的跨语言 API,用于访问和修改 XML 文档。 DOM 的实现将 XML 文档以树结构表示,或者允许客户端代码从头构建这样的结构。 然后它会通过一组提供通用接口的对象赋予对结构的访问权。

DOM 特别适用于进行随机访问的应用。 SAX 仅允许你每次查看文档的一小部分。 如果你正在查看一个 SAX 元素,你将不能访问其他元素。 如果你正在查看一个文本节点,你将不能访问包含它的元素。 当你编写一个 SAX 应用时,你需要在你自己的代码的某个地方记住你的程序在文档中的位置。 SAX 不会帮你做这件事。 并且,如果你想要在 XML 文档中向前查看,你是绝对办不到的。

有些应用程序在不能访问树的事件驱动模型中是根本无法编写的。 当然你可以在 SAX 事件中自行构建某种树,但是 DOM 可以使你避免编写这样的代码。 DOM 是针对 XML 数据的标准树表示形式。

文档对象模型是由 W3C 分阶段定义的,在其术语中称为“层级”。 Python 中该 API 的映射大致是基于 DOM 第 2 层级的建议。

DOM 应用程序通常从将某些 XML 解析为 DOM 开始。 此操作如何实现完全未被 DOM 第 1 层级所涉及,而第 2 层级也只提供了有限的改进:有一个 DOMImplementation 对象类,它提供对 Document 创建方法的访问,但却没有办法以不依赖具体实现的方式访问 XML 读取器/解析器/文档创建器。 也没有当不存在 Document 对象的情况下访问这些方法的定义良好的方式。 在 Python 中,每个 DOM 实现将提供一个函数 getDOMImplementation()。 DOM 第 3 层级增加了一个载入/存储规格说明,它定义了与读取器的接口,但这在 Python 标准库中尚不可用。

一旦你得到了 DOM 文档对象,你就可以通过 XML 文档的属性和方法访问它的各个部分。 这些属性定义在 DOM 规格说明当中;参考指南的这一部分描述了 Python 对此规格说明的解读。

W3C 提供的规格说明定义了适用于 Java, ECMAScript 和 OMG IDL 的 DOM API。 这里定义的 Python 映射很大程度上是基于此规格说明的 IDL 版本,但并不要求严格映射(但具体实现可以自由地支持对 IDL 的严格映射)。 请参阅 一致性 一节查看有关映射要求的详细讨论。

参见

文档对象模型 (DOM) 第 2 层级规格说明

被 Python DOM API 作为基础的 W3C 建议。

文档对象模型 (DOM) 第 1 层级规格说明

xml.dom.minidom 所支持的 W3C 针对 DOM 的建议。

Python 语言映射规格说明

此文档指明了从 OMG IDL 到 Python 的映射。

模块内容

xml.dom 包含以下函数:

xml.dom.registerDOMImplementation(name, factory)

注册 factory 函数并使用名称 name。 该工厂函数应当返回一个实现了 DOMImplementation 接口的对象。 该工厂函数可每次都返回相同对象,或每次调用都返回新的对象,视具体实现的要求而定(例如该实现是否支持某些定制功能)。

xml.dom.getDOMImplementation(name=None, features=())

Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns a DOMImplementation object if the import succeeds. If no name is given, and if the environment variable PYTHON_DOM is set, this variable is used to find the implementation. The only well-known name in the standard library is 'minidom', for xml.dom.minidom.

If name is not given, this examines the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature, version) pairs which are passed to the hasFeature() method on available DOMImplementation objects.

还提供了一些便捷常量:

xml.dom.EMPTY_NAMESPACE

The value used to indicate that no namespace is associated with a node in the DOM. This is typically found as the namespaceURI of a node, or used as the namespaceURI parameter to a namespaces-specific method.

xml.dom.XML_NAMESPACE

关联到保留前缀 xml 的命名空间 URI,如 XML 中的命名空间 (第 4 节) 所定义的。

xml.dom.XMLNS_NAMESPACE

命名空间声明的命名空间 URI,如 文档对象模型 (DOM) 第 2 层级核心规格说明 (第 1.1.8节) 所定义的。

xml.dom.XHTML_NAMESPACE

XHTML 命名空间的 URI,如 XHTML 1.0: 扩展超文本标记语言 (第 3.1.1 节) 所定义的。

In addition, xml.dom contains a base Node class and the DOM exception classes. The Node class provided by this module does not implement any of the methods or attributes defined by the DOM specification; concrete DOM implementations must provide those. The Node class provided as part of this module does provide the constants used for the nodeType attribute on concrete Node objects; they are located within the class rather than at the module level to conform with the DOM specifications.

DOM 中的对象

DOM 的权威文档是来自 W3C 的 DOM 规格描述。

The names documented in this section are DOM interfaces. With the exception of Node and the exception classes, they are not provided by the xml.dom module itself, but by concrete DOM implementations, such as xml.dom.minidom.

请注意,DOM 属性也可以作为节点而不是简单的字符串进行操作。 然而,必须这样做的情况相当少见,所以这种用法还没有被写入文档。

接口

小节

目的

DOMImplementation

DOMImplementation 对象

底层实现的接口。

Node

节点对象

文档中大多数对象的基本接口。

NodeList

节点列表对象

节点序列的接口。

DocumentType

文档类型对象

有关处理文档所需声明的信息。

Document

Document 对象

表示整个文档的对象。

Element

元素对象

文档层次结构中的元素节点。

Attr

Attr 对象

元素节点上的属性值节点。

Comment

注释对象

源文档中注释的表示形式。

Text

Text 和 CDATASection 对象

包含文档中文本内容的节点。

ProcessingInstruction

ProcessingInstruction 对象

处理指令表示形式。

额外的小节描述了在 Python 中使用 DOM 所定义的异常。

DOMImplementation 对象

DOMImplementation 接口提供了一种让应用程序确定他们所使用的 DOM 中某一特性可用性的方式。 DOM 第 2 级还添加了使用 DOMImplementation 来创建新的 DocumentDocumentType 对象的能力。

DOMImplementation.hasFeature(feature, version)

如果字符串对 featureversion 所标识的特性已被实现则返回 True

DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)

返回一个新的 Document 对象 (DOM 的根节点),包含一个具有给定 namespaceUriqualifiedName 的下级 Element 对象。 doctype 必须为由 createDocumentType() 创建的 DocumentType 对象,或者为 None。 在 Python DOM API 中,前两个参数也可为 None 以表示不要创建任何下级 Element

DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)

返回一个新的封装了给定 qualifiedName, publicIdsystemId 字符串的 DocumentType 对象,它表示包含在 XML 文档类型声明中的信息。

节点对象

XML 文档的所有组成部分都是 Node 的子类。

Only nodes of the following types can have children, and only children of the listed types:

Document

at most one Element, at most one DocumentType, ProcessingInstruction and Comment

DocumentFragment and Element

Element, Text, CDATASection, ProcessingInstruction and Comment

Attr

Text

Nodes of other types cannot have children. Inserting a child of a not allowed type raises HierarchyRequestErr.

Node.nodeType

An integer representing the node type. Symbolic constants for the types are on the Node object. This is a read-only attribute.

Node.ELEMENT_NODE
Node.ATTRIBUTE_NODE
Node.TEXT_NODE
Node.CDATA_SECTION_NODE
Node.ENTITY_REFERENCE_NODE
Node.ENTITY_NODE
Node.PROCESSING_INSTRUCTION_NODE
Node.COMMENT_NODE
Node.DOCUMENT_NODE
Node.DOCUMENT_TYPE_NODE
Node.DOCUMENT_FRAGMENT_NODE
Node.NOTATION_NODE

Integer constants for the possible values of the nodeType attribute.

Node.parentNode

当前节点的上级,或者对于文档节点则为 None。 该值总是一个 Node 对象或者 None。 对于 Element 节点,这将为上级元素,但对于根元素例外,在此情况下它将为 Document 对象。 对于 Attr 节点,它将总是为 None。 这是个只读属性。

Node.attributes

属性对象的 NamedNodeMap。 这仅对元素才有实际值;其它对象会为该属性提供 None 值。 这是个只读属性。

Node.previousSibling

在此节点之前具有相同上级的相邻节点。 例如结束标记紧接在 self 元素的开始标记之前的元素。 当然,XML 文档并非只是由元素组成,因此之前相邻节点可以是文本、注释或者其他内容。 如果此节点是上级的第一个子节点,则该属性将为 None。 这是一个只读属性。

Node.nextSibling

在此节点之后具有相同上级的相邻节点。 另请参见 previousSibling。 如果此节点是上级的最后一个子节点,则该属性将为 None。 这是一个只读属性。

Node.childNodes

A NodeList of the children of this node. If the node has no children, the list is empty. This is a read-only attribute.

Node.firstChild

节点的第一个下级,如果有的话,否则为 None。 这是个只读属性。

Node.lastChild

节点的最后一个下级,如果有的话,否则为 None。 这是个只读属性。

Node.localName

The part of the tagName following the colon if there is one, else the entire tagName. The value is a string.

Node.prefix

The part of the tagName preceding the colon if there is one, else the empty string. The value is a string, or None.

Node.namespaceURI

关联到元素名称的命名空间。 这将是一个字符串或为 None。 这是个只读属性。

Node.ownerDocument

The Document object to which this node belongs, or None for a document itself. This is a read-only attribute.

Node.isSupported(feature, version)

Return whether the DOM implementation supports a particular feature, as DOMImplementation.hasFeature() does.

Node.setUserData(key, data, handler)

Associate data with key on this node and return the data previously associated with key, or None. If data is None, the association is removed. handler is called when the node is cloned, imported, renamed or deleted; pass None if no notification is needed.

Node.getUserData(key)

Return the data associated with key on this node by setUserData(), or None.

Node.nodeName

The name of this node, depending on its type; see the table below. You can always get the information you would get here from another property such as the tagName property for elements or the name property for attributes. This is a read-only attribute.

Node.nodeValue

The value of this node, depending on its type; see the table below. The value is a string or None.

The values of nodeName and nodeValue for each node type are:

Node type

nodeName

nodeValue

Attr

name

value

CDATASection

'#cdata-section'

the content

Comment

'#comment'

the content

Document

'#document'

None

DocumentFragment

'#document-fragment'

None

DocumentType

name

None

Element

tagName

None

Entity

the name of the entity

None

Notation

the name of the notation

None

ProcessingInstruction

target

data

Text

'#text'

the content

Node.hasAttributes()

如果该节点具有任何属性则返回 True

Node.hasChildNodes()

如果该节点具有任何子节点则返回 True

Node.isSameNode(other)

如果 other 指向的节点就是此节点则返回 True。 这对于使用了任何代理架构的 DOM 实现来说特别有用(因为多个对象可能指向相同节点)。

备注

这是基于已提议的 DOM 第 3 层级 API,目前尚处于“起草”阶段,但这个特定接口看来并不存在争议。 来自 W3C 的修改将不会影响 Python DOM 接口中的这个方法(不过针对它的任何新 W3C API 也将受到支持)。

Node.appendChild(newChild)

在子节点列表末尾添加一个新的子节点,返回 newChild。 如果节点已存在于树结构中,它将先被移除。

Node.insertBefore(newChild, refChild)

Insert a new child node before an existing child. It must be the case that refChild is a child of this node; if not, NotFoundErr is raised. newChild is returned. If refChild is None, it inserts newChild at the end of the children's list.

Node.removeChild(oldChild)

Remove a child node. oldChild must be a child of this node; if not, NotFoundErr is raised. oldChild is returned on success. If oldChild will not be used further, its unlink() method should be called.

Node.replaceChild(newChild, oldChild)

Replace an existing node with a new node. It must be the case that oldChild is a child of this node; if not, NotFoundErr is raised.

Node.normalize()

合并相邻的文本节点以便将所有文本段存储为单个 Text 实例。 这可以简化许多应用程序处理来自 DOM 树文本的操作。

Node.cloneNode(deep)

克隆此节点。 设置 deep 表示也克隆所有子节点。 此方法将返回克隆的节点。

节点列表对象

A NodeList represents a sequence of nodes. These objects are used in two ways in the DOM Core recommendation: an Element object provides one as its list of child nodes, and the getElementsByTagName() and getElementsByTagNameNS() methods of Node return objects with this interface to represent query results.

NodeList does not inherit from Node.

DOM 第 2 层级建议为这些对象定义一个方法和一个属性:

NodeList.item(i)

Return the i'th item from the sequence, or None if i is out of range. Negative indices are not supported.

NodeList.length

序列中的节点数量。

此外,Python DOM 接口还要求提供一些额外支持来允许将 NodeList 对象用作 Python 序列。 所有 NodeList 实现都必须包括对 __len__()__getitem__() 的支持;这样 NodeList 就允许使用 for 语句进行迭代并能正确地支持 len() 内置函数。

如果一个 DOM 实现支持文档的修改,则 NodeList 实现还必须支持 __setitem__()__delitem__() 方法。

文档类型对象

Information about the notations and entities declared by a document (including the external subset if the parser uses it and can provide the information) is available from a DocumentType object. The DocumentType for a document is available from the Document object's doctype attribute; if there is no DOCTYPE declaration for the document, the document's doctype attribute will be set to None instead of an instance of this interface.

DocumentTypeNode 的专门化,并增加了下列属性:

DocumentType.publicId

The public identifier for the external subset of the document type definition, or None if the DOCTYPE declaration does not specify it.

DocumentType.systemId

The system identifier, a URI, for the external subset of the document type definition, or None if the DOCTYPE declaration does not specify it.

DocumentType.internalSubset

一个给出来自文档的完整内部子集的字符串。 这不包括子集外面的方括号。 如果文档没有内部子集,则应为 None

DocumentType.name

DOCTYPE 声明中给出的根元素名称,如果有的话。

DocumentType.entities

This is a NamedNodeMap of Entity nodes giving the definitions of external entities. For entity names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). This may be None if the information is not provided by the parser, or if no entities are defined.

DocumentType.notations

This is a NamedNodeMap of Notation nodes giving the definitions of notations. For notation names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). This may be None if the information is not provided by the parser, or if no notations are defined.

Document 对象

Document 代表一个完整的 XML 文档,包括其组成元素、属性、处理指令和注释等。 请记住它会继承来自 Node 的属性。

Document.documentElement

文档唯一的根元素。

Document.doctype

The DocumentType node of the document, or None. This is a read-only attribute.

Document.implementation

The DOMImplementation object which created this document. This is a read-only attribute.

Document.strictErrorChecking

Whether error checking is enforced.

Document.documentURI

The location of the document, or None if it is unknown.

Document.createDocumentFragment()

Create and return an empty DocumentFragment node.

Document.createCDATASection(data)

Create and return a CDATASection node containing data.

Document.importNode(importedNode, deep)

Return a copy of importedNode which belongs to this document. The original node is not removed from its document. If deep is true, the descendants of the node are copied too.

Document.createElement(tagName)

Create and return a new element node. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().

Document.createElementNS(namespaceURI, tagName)

Create and return a new element with a namespace. The tagName may have a prefix. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().

Document.createTextNode(data)

创建并返回一个包含作为形参被传入的数据的文本节点。 与其他创建方法一样,此方法不会将节点插入到树中。

Document.createComment(data)

创建并返回一个包含作为形参被传入的数据的注释节点。 与其他创建方法一样,此方法不会将节点插入到树中。

Document.createProcessingInstruction(target, data)

创建并返回一个包含作为形参被传入的 targetdata 的处理指令节点。 与其他创建方法一样,此方法不会将节点插入到树中。

Document.createAttribute(name)

Create and return an attribute node. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.

Document.createAttributeNS(namespaceURI, qualifiedName)

Create and return an attribute node with a namespace. The tagName may have a prefix. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.

Document.getElementById(id)

Return the element with the given ID, or None. Only attributes declared as being of type ID in the DTD or by Element.setIdAttribute() are searched.

Document.getElementsByTagName(tagName)

搜索全部具有特定元素类型名称的后继元素(直接下级、下级的下级等等)。

Document.getElementsByTagNameNS(namespaceURI, localName)

搜索全部具有特定命名空间 URI 和 localname 的后继元素(直接下级、下级的下级等等)。 localname 是命名空间在前缀之后的部分。

Document.renameNode(n, namespaceURI, name)

Rename the element or attribute node n and return it. namespaceURI is the new namespace URI, or EMPTY_NAMESPACE if the node does not belong to a namespace. name is the new qualified name.

Raise WrongDocumentErr if n was created by another document, and NotSupportedErr if it is neither an element nor an attribute.

元素对象

ElementNode 的子类,因此会继承该类的全部属性。

Element.tagName

元素类型名称。 在使用命名空间的文档中它可能包含冒号。 该值是一个字符串。

Element.setIdAttribute(name)

Declare that the attribute name is of type ID, so that the element is found by Document.getElementById(). Raise NotFoundErr if the element has no such attribute.

Element.setIdAttributeNS(namespaceURI, localName)

The same as setIdAttribute(), but for an attribute specified by its namespace URI and local name.

Element.setIdAttributeNode(idAttr)

The same as setIdAttribute(), but for an already retrieved attribute node.

Element.getElementsByTagName(tagName)

Document 类中的对应方法相同。

Element.getElementsByTagNameNS(namespaceURI, localName)

Document 类中的对应方法相同。

Element.hasAttribute(name)

如果元素带有名称为 name 的属性则返回 True

Element.hasAttributeNS(namespaceURI, localName)

如果元素带有名称为 namespaceURIlocalName 的属性则返回 True

Element.getAttribute(name)

将名称为 name 的属性的值作为字符串返回。 如果指定属性不存在,则返回空字符串,就像该属性没有对应的值一样。

Element.getAttributeNode(attrname)

返回名称为 attrname 的属性对应的 Attr 节点。

Element.getAttributeNS(namespaceURI, localName)

将名称为 namespaceURIlocalName 的属性的值作为字符串返回。 如果指定属性不存在,则返回空字符串,就像该属性没有对应的值一样。

Element.getAttributeNodeNS(namespaceURI, localName)

将给定 namespaceURIlocalName 的属性的值作为节点返回。

Element.removeAttribute(name)

Remove an attribute by name.

Element.removeAttributeNode(oldAttr)

从属性列表中移除并返回 oldAttr,如果该属性存在的话。 如果 oldAttr 不存在,则会引发 NotFoundErr

Element.removeAttributeNS(namespaceURI, localName)

Remove an attribute by name. Note that it uses a localName, not a qname.

Element.setAttribute(name, value)

将属性值设为指定的字符串。

Element.setAttributeNode(newAttr)

Add a new attribute node to the element, replacing an existing attribute if necessary if the name attribute matches. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use, InuseAttributeErr will be raised.

Element.setAttributeNodeNS(newAttr)

Add a new attribute node to the element, replacing an existing attribute if necessary if the namespaceURI and localName attributes match. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use, InuseAttributeErr will be raised.

Element.setAttributeNS(namespaceURI, qname, value)

将属性值设为 namespaceURIqname 所给出的字符串。 请注意 qname 是整个属性名称。 这与上面的方法不同。

Attr 对象

Attr 继承自 Node,因此会继承其全部属性。

Attribute nodes are not part of the document tree. They are contained in the attributes map of an element, not in its children, and their parentNode, previousSibling and nextSibling are always None.

Attr.name

属性名称。 在使用命名空间的文档中可能会包括冒号。

Attr.localName

名称在冒号之后的部分,如果有的话,否则为完整名称。 这是个只读属性。

Attr.prefix

名称在冒号之前的部分,如果有冒号的话,否则为空字符串。

Attr.isId

Whether this attribute is of type ID, either because it is declared as such in the DTD or because Element.setIdAttribute() was used. This is a read-only attribute.

Attr.ownerElement

The Element node to which this attribute belongs, or None if it is not used. This is a read-only attribute.

Attr.specified

Whether the value of the attribute was explicitly set in the document, as opposed to being defaulted from the DTD. This is a read-only attribute.

Attr.value

The text value of the attribute. This is a synonym for the nodeValue attribute.

NamedNodeMap 对象

NamedNodeMap 不是 继承自 Node

NamedNodeMap.length

属性列表的长度。

NamedNodeMap.item(index)

Return an attribute with a particular index. The order you get the attributes in is arbitrary but will be consistent for the life of a DOM. Each item is an attribute node. Get its value with the value attribute.

NamedNodeMap.getNamedItem(name)

Return the node with the given name, or None if there is no such node.

NamedNodeMap.getNamedItemNS(namespaceURI, localName)

Return the node with the given namespace URI and local name, or None if there is no such node.

NamedNodeMap.setNamedItem(node)

Add node to the map, using its name as the key. Return the node which it replaces, or None if it replaces no node.

NamedNodeMap.setNamedItemNS(node)

Add node to the map, using its namespace URI and local name as the key. Return the node which it replaces, or None if it replaces no node.

NamedNodeMap.removeNamedItem(name)

Remove and return the node with the given name. Raise NotFoundErr if there is no such node.

NamedNodeMap.removeNamedItemNS(namespaceURI, localName)

Remove and return the node with the given namespace URI and local name. Raise NotFoundErr if there is no such node.

You can also use the standardized getAttribute*() family of methods on the Element objects.

DocumentFragment Objects

DocumentFragment is a lightweight container of nodes. It is a subclass of Node. When it is inserted into the document tree, its children are inserted instead of it, and it becomes empty.

CharacterData Objects

CharacterData represents text-like data in the XML document. It is a subclass of Node, and the base class of Text, CDATASection and Comment. Such nodes cannot have child nodes.

CharacterData.data

The content of the node as a string.

CharacterData.length

The number of characters in data. This is a read-only attribute.

CharacterData.substringData(offset, count)

Return the substring of data of count characters starting at offset.

CharacterData.appendData(arg)

Append the string arg to data.

CharacterData.insertData(offset, arg)

Insert the string arg into data at offset.

CharacterData.deleteData(offset, count)

Remove count characters from data starting at offset.

CharacterData.replaceData(offset, count, arg)

Replace count characters of data starting at offset with the string arg.

注释对象

Comment represents a comment in the XML document. It is a subclass of CharacterData.

Comment.data

注释的内容是一个字符串。 该属性包含在开头 <!-- 和末尾 --> 之间的所有字符,但不包括这两个符号。

Text 和 CDATASection 对象

The Text interface represents text in the XML document. If the parser and DOM implementation support the DOM's XML extension, portions of the text enclosed in CDATA marked sections are stored in CDATASection objects. These two interfaces are identical, but provide different values for the nodeType attribute.

Text extends the CharacterData interface, and CDATASection extends Text.

Text.data

字符串形式的文本节点内容。

Text.wholeText

The text of all Text nodes logically adjacent to this node, concatenated in document order. This is a read-only attribute.

Text.replaceWholeText(content)

Replace the text of all Text nodes logically adjacent to this node with content, removing the other nodes. Return this node, or None if content is empty.

Text.splitText(offset)

Split this node into two nodes at offset, keeping the first part in this node and returning a new sibling node with the rest.

备注

CDATASection 节点的使用并不表示该节点代表一个完整的 CDATA 标记节,只是表示该节点的内容是 CDATA 节的一部分。 单个 CDATA 节可以由文档树中的多个节点来表示。 没有什么办法能确定两个相邻的 CDATASection 节点是否代表不同的 CDATA 标记节。

ProcessingInstruction 对象

代表 XML 文档中的处理指令。 它继承自 Node 接口并且不能拥有下级节点。

ProcessingInstruction.target

到第一个空格符为止的处理指令内容。 这是个只读属性。

ProcessingInstruction.data

在第一个空格符之后的处理指令内容。

Entity Objects

Entity represents a parsed or unparsed entity declared in the DTD. It is a subclass of Node. Entity nodes are contained in DocumentType.entities and cannot be inserted into the document tree. The name of the entity is its nodeName.

Entity.publicId

The public identifier of the entity, or None if it is not specified. This is a read-only attribute.

Entity.systemId

The system identifier of the entity, or None if it is not specified. This is a read-only attribute.

Entity.notationName

The name of the notation for an unparsed entity, or None for a parsed entity. This is a read-only attribute.

Notation Objects

Notation represents a notation declared in the DTD. It is a subclass of Node and cannot have child nodes. Notation nodes are contained in DocumentType.notations and cannot be inserted into the document tree. The name of the notation is its nodeName.

Notation.publicId

The public identifier of the notation, or None if it is not specified. This is a read-only attribute.

Notation.systemId

The system identifier of the notation, or None if it is not specified. This is a read-only attribute.

异常

DOM 第 2 层级建议定义了一个异常 DOMException,以及多个常量用来允许应用程序确定发生了何种错误。 DOMException 实例带有 code 属性用来提供特定异常所对应的值。

Python DOM 接口提供了一些常量,但还扩展了异常集以使 DOM 所定义的每个异常代码都存在特定的异常。 接口的具体实现必须引发正确的特定异常,它们各自带有正确的 code 属性值。

exception xml.dom.DOMException

所有特定 DOM 异常所使用的异常基类。 该异常类不可被直接实例化。

exception xml.dom.DomstringSizeErr

当指定范围的文本不能适配一个字符串时被引发。 此异常不确定是否在 Python DOM 实现中被使用过,但可从不是以 Python 编写的 DOM 实现中接收。

exception xml.dom.HierarchyRequestErr

当尝试插入一个节点但该节点类型不被允许时被引发。

exception xml.dom.IndexSizeErr

当一个方法的索引或大小参数为负值或超出允许的值范围时被引发。

exception xml.dom.InuseAttributeErr

当尝试插入一个 Attr 节点但该节点已存在于文档中的某处时被引发。

exception xml.dom.InvalidAccessErr

当某个参数或操作在底层对象中不受支持时被引发。

exception xml.dom.InvalidCharacterErr

当某个字符串参数包含的字符在使用它的上下文中不被 XML 1.0 标准建议所允许时引发。 例如,尝试创建一个元素类型名称中带有空格的 Element 节点将导致此错误被引发。

exception xml.dom.InvalidModificationErr

当尝试修改某个节点的类型时被引发。

exception xml.dom.InvalidStateErr

当尝试使用未定义或不再可用的对象时被引发。

exception xml.dom.NamespaceErr

如果试图以 XML 中的命名空间 建议所不允许的方式修改任何对象,则会引发此异常。

exception xml.dom.NotFoundErr

当某个节点不存在于被引用的上下文中时引发的异常。 例如,NamedNodeMap.removeNamedItem() 将在所传入的节点不存在于映射中时引发此异常。

exception xml.dom.NotSupportedErr

当具体实现不支持所请求的对象类型或操作时被引发。

exception xml.dom.NoDataAllowedErr

当为某个不支持数据的节点指定数据时被引发。

exception xml.dom.NoModificationAllowedErr

当尝试修改某个不允许修改的对象(例如只读节点)时被引发。

exception xml.dom.SyntaxErr

当指定了无效或非法的字符串时被引发。

exception xml.dom.ValidationErr

Raised when an operation would make the document invalid with respect to partial validity. This is not known to be used in the Python DOM implementations, but may be received from DOM implementations not written in Python.

exception xml.dom.WrongDocumentErr

当将某个节点插入非其当前所属的另一个文档,并且具体实现不支持从一个文档向另一个文档迁移节点时被引发。

DOM 建议映射中针对上述异常而定义的异常代码如下表所示:

常量

异常

xml.dom.DOMSTRING_SIZE_ERR

DomstringSizeErr

xml.dom.HIERARCHY_REQUEST_ERR

HierarchyRequestErr

xml.dom.INDEX_SIZE_ERR

IndexSizeErr

xml.dom.INUSE_ATTRIBUTE_ERR

InuseAttributeErr

xml.dom.INVALID_ACCESS_ERR

InvalidAccessErr

xml.dom.INVALID_CHARACTER_ERR

InvalidCharacterErr

xml.dom.INVALID_MODIFICATION_ERR

InvalidModificationErr

xml.dom.INVALID_STATE_ERR

InvalidStateErr

xml.dom.NAMESPACE_ERR

NamespaceErr

xml.dom.NOT_FOUND_ERR

NotFoundErr

xml.dom.NOT_SUPPORTED_ERR

NotSupportedErr

xml.dom.NO_DATA_ALLOWED_ERR

NoDataAllowedErr

xml.dom.NO_MODIFICATION_ALLOWED_ERR

NoModificationAllowedErr

xml.dom.SYNTAX_ERR

SyntaxErr

xml.dom.VALIDATION_ERR

ValidationErr

xml.dom.WRONG_DOCUMENT_ERR

WrongDocumentErr

一致性

本节描述了 Python DOM API、W3C DOM 建议以及 Python 的 OMG IDL 映射之间的一致性要求和关系。

类型映射

DOM 规范中使用的 IDL 类型将根据下表映射为 Python 类型。

IDL 类型

Python 类型

boolean

boolint

int

int

long int

int

unsigned int

int

DOMString

strbytes

null

None

访问器方法

从 OMG IDL 到 Python 的映射以类似于 Java 映射的方式定义了针对 IDL attribute 声明的访问器函数。 映射以下 IDL 声明

readonly attribute string someValue;
         attribute string anotherValue;

yields three accessor functions: a "get" method for someValue (_get_someValue()), and "get" and "set" methods for anotherValue (_get_anotherValue() and _set_anotherValue()). The mapping, in particular, does not require that the IDL attributes are accessible as normal Python attributes: object.someValue is not required to work, and may raise an AttributeError.

但是,Python DOM API 则 确实 要求普通属性访问可用。 这意味着由 Python IDL 解译器生成的典型代理有可能会不可用,如果 DOM 对象是通过 CORBA 来访问则在客户端可能需要有包装对象。 虽然这确实要求为 CORBA DOM 客户端进行额外的考虑,但具有从 Python 通过 CORBA 使用 DOM 经验的实现并不会认为这是个问题。 已经声明了 readonly 的属性不必在所有 DOM 实现中限制写入访问。

在 Python DOM API 中,访问器函数不是必须的。 如果提供,则它们应当采用由 Python IDL 映射所定义的形式,但这些方法会被认为不必要,因为这些属性可以从 Python 直接访问。 永远都不要为 readonly 属性提供 "set" 访问器。

The IDL definitions do not fully embody the requirements of the W3C DOM API, such as the notion of certain objects, such as the return value of getElementsByTagName(), being "live". The Python DOM API does not require implementations to enforce such requirements.