xml.domThe Document Object Model API文档对象模型API

Source code: Lib/xml/dom/__init__.py


The Document Object Model, or “DOM,” is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents. 文档对象模型或“DOM”是万维网联盟(W3C)的一个跨语言API,用于访问和修改XML文档。A DOM implementation presents an XML document as a tree structure, or allows client code to build such a structure from scratch. DOM实现将XML文档呈现为树结构,或者允许客户端代码从头开始构建这样的结构。It then gives access to the structure through a set of objects which provided well-known interfaces.然后,它通过一组提供了众所周知的接口的对象来访问该结构。

The DOM is extremely useful for random-access applications. DOM对于随机访问应用程序非常有用。SAX only allows you a view of one bit of the document at a time. SAX一次只允许查看文档的一部分。If you are looking at one SAX element, you have no access to another. 如果您正在查看一个SAX元素,则无法访问另一个。If you are looking at a text node, you have no access to a containing element. 如果您正在查看文本节点,则无法访问包含元素。When you write a SAX application, you need to keep track of your program’s position in the document somewhere in your own code. 当您编写SAX应用程序时,您需要在自己的代码中的某个位置跟踪程序在文档中的位置。SAX does not do it for you. SAX不会为你做这件事。Also, if you need to look ahead in the XML document, you are just out of luck.此外,如果您需要在XML文档中向前看,那么您就走运了。

Some applications are simply impossible in an event driven model with no access to a tree. 有些应用程序在事件驱动模型中根本不可能访问树。Of course you could build some sort of tree yourself in SAX events, but the DOM allows you to avoid writing that code. 当然,您可以自己在SAX事件中构建某种树,但DOM允许您避免编写该代码。The DOM is a standard tree representation for XML data.DOM是XML数据的标准树表示。

The Document Object Model is being defined by the W3C in stages, or “levels” in their terminology. 文档对象模型是由W3C分阶段定义的,或者用他们的术语来定义“级别”。The Python mapping of the API is substantially based on the DOM Level 2 recommendation.API的Python映射基本上基于DOM级别2建议。

DOM applications typically start by parsing some XML into a DOM. DOM应用程序通常从将一些XML解析为DOM开始。How this is accomplished is not covered at all by DOM Level 1, and Level 2 provides only limited improvements: There is a DOMImplementation object class which provides access to Document creation methods, but no way to access an XML reader/parser/Document builder in an implementation-independent way. DOM级别1根本没有涉及如何实现这一点,而级别2只提供了有限的改进:有一个DOMIplementation对象类提供了对文档创建方法的访问,但无法以独立于实现的方式访问XML阅读器/解析器/文档构建器。There is also no well-defined way to access these methods without an existing Document object. 在没有现有Document对象的情况下,也没有明确定义的方法来访问这些方法。In Python, each DOM implementation will provide a function getDOMImplementation(). 在Python中,每个DOM实现都将提供一个函数getDOMImplementation()DOM Level 3 adds a Load/Store specification, which defines an interface to the reader, but this is not yet available in the Python standard library.DOM级别3添加了加载/存储规范,该规范定义了读取器的接口,但这在Python标准库中尚不可用。

Once you have a DOM document object, you can access the parts of your XML document through its properties and methods. 一旦有了DOM文档对象,就可以通过其属性和方法访问XML文档的各个部分。These properties are defined in the DOM specification; this portion of the reference manual describes the interpretation of the specification in Python.这些属性在DOM规范中定义;参考手册的这一部分描述了对Python规范的解释。

The specification provided by the W3C defines the DOM API for Java, ECMAScript, and OMG IDL. W3C提供的规范定义了Java、ECMAScript和OMG IDL的DOM API。The Python mapping defined here is based in large part on the IDL version of the specification, but strict compliance is not required (though implementations are free to support the strict mapping from IDL). 这里定义的Python映射在很大程度上基于规范的IDL版本,但不需要严格遵守(尽管实现可以自由支持来自IDL的严格映射)。See section Conformance for a detailed discussion of mapping requirements.有关映射要求的详细讨论,请参阅“一致性”一节。

See also另请参见

Document Object Model (DOM) Level 2 Specification文档对象模型(DOM)2级规范

The W3C recommendation upon which the Python DOM API is based.Python DOM API所基于的W3C建议。

Document Object Model (DOM) Level 1 Specification文档对象模型(DOM)1级规范

The W3C recommendation for the DOM supported by xml.dom.minidom.W3C对xml.dom.minidom支持的DOM的建议。

Python Language Mapping SpecificationPython语言映射规范

This specifies the mapping from OMG IDL to Python.这指定了从OMG IDL到Python的映射。

Module Contents模块内容

The xml.dom contains the following functions:xml.dom包含以下函数:

xml.dom.registerDOMImplementation(name, factory)

Register the factory function with the name name. 使用name注册factory函数。The factory function should return an object which implements the DOMImplementation interface. 工厂函数应该返回一个实现DOMIplementation接口的对象。The factory function can return the same object every time, or a new one for each call, as appropriate for the specific implementation (e.g. if that implementation supports some customization).工厂函数可以每次返回同一个对象,或者每次调用都返回一个新的对象,这取决于特定的实现(例如,如果该实现支持某种定制)。

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

Return a suitable DOM implementation. 返回合适的DOM实现。The name is either well-known, the module name of a DOM implementation, or None. name要么是众所周知的,要么是DOM实现的模块名称,要么是NoneIf it is not None, imports the corresponding module and returns a DOMImplementation object if the import succeeds. 如果不是None,则导入相应的模块,如果导入成功,则返回DOMImplementation对象。If no name is given, and if the environment variable PYTHON_DOM is set, this variable is used to find the implementation.如果没有给定名称,并且设置了环境变量PYTHON_DOM,则使用此变量查找实现。

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. 如果找不到实现,则引发ImportErrorThe features list must be a sequence of (feature, version) pairs which are passed to the hasFeature() method on available DOMImplementation objects.功能列表必须是一系列(feature, version)对,这些对传递给可用DOMImplementation对象上的hasFeature()方法。

Some convenience constants are also provided:还提供了一些方便常数:

xml.dom.EMPTY_NAMESPACE

The value used to indicate that no namespace is associated with a node in the DOM. 用于指示没有命名空间与DOM中的节点关联的值。This is typically found as the namespaceURI of a node, or used as the namespaceURI parameter to a namespaces-specific method.这通常作为节点的namespaceURI,或用作命名空间特定方法的namespaceURI参数。

xml.dom.XML_NAMESPACE

The namespace URI associated with the reserved prefix xml, as defined by Namespaces in XML (section 4).与保留前缀xml关联的命名空间URI,由xml中的命名空间定义(第4节)。

xml.dom.XMLNS_NAMESPACE

The namespace URI for namespace declarations, as defined by Document Object Model (DOM) Level 2 Core Specification (section 1.1.8).命名空间声明的命名空间URI,由文档对象模型(DOM)2级核心规范(第1.1.8节)定义。

xml.dom.XHTML_NAMESPACE

The URI of the XHTML namespace as defined by XHTML 1.0: The Extensible HyperText Markup Language (section 3.1.1).XHTML 1.0:可扩展超文本标记语言(第3.1.1节)定义的XHTML命名空间的URI。

In addition, xml.dom contains a base Node class and the DOM exception classes. 此外,xml.dom包含一个基本Node类和DOM异常类。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. 该模块提供的Node类不实现DOM规范定义的任何方法或属性;具体的DOM实现必须提供这些。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.作为此模块的一部分提供的Node类确实提供了用于具体Node对象的nodeType属性的常量;它们位于类内而不是模块级,以符合DOM规范。

Objects in the DOMDOM中的对象

The definitive documentation for the DOM is the DOM specification from the W3C.DOM的最终文档是W3C的DOM规范。

Note that DOM attributes may also be manipulated as nodes instead of as simple strings. 请注意,DOM属性也可以作为节点而不是简单字符串来操作。It is fairly rare that you must do this, however, so this usage is not yet documented.但是,您必须这样做的情况非常罕见,因此这种用法尚未被记录下来。

Interface界面

Section部分

Purpose意图

DOMImplementation

DOMImplementation Objects对象

Interface to the underlying implementation.底层实现的接口。

Node

Node Objects对象

Base interface for most objects in a document.文档中大多数对象的基本界面。

NodeList

NodeList Objects对象

Interface for a sequence of nodes.节点序列的接口。

DocumentType

DocumentType ObjectsDocumentType对象

Information about the declarations needed to process a document.有关处理文档所需声明的信息。

Document

Document Objects对象

Object which represents an entire document.表示整个文档的对象。

Element

Element Objects对象

Element nodes in the document hierarchy.文档层次结构中的元素节点。

Attr

Attr Objects对象

Attribute value nodes on element nodes.元素节点上的属性值节点。

Comment

Comment Objects对象

Representation of comments in the source document.源文档中注释的表示。

Text

Text and CDATASection ObjectsText对象和CDATASection对象

Nodes containing textual content from the document.包含文档中文本内容的节点。

ProcessingInstruction

ProcessingInstruction Objects对象

Processing instruction representation.处理指令表示。

An additional section describes the exceptions defined for working with the DOM in Python.另外一节描述了为在Python中使用DOM而定义的异常。

DOMImplementation Objects对象

The DOMImplementation interface provides a way for applications to determine the availability of particular features in the DOM they are using. DOMIplementation接口为应用程序提供了一种方法,以确定它们正在使用的DOM中特定功能的可用性。DOM Level 2 added the ability to create new Document and DocumentType objects using the DOMImplementation as well.DOM级别2还添加了使用DOMImplementation创建新的DocumentDocumentType对象的能力。

DOMImplementation.hasFeature(feature, version)

Return True if the feature identified by the pair of strings feature and version is implemented.如果实现了由一对字符串featureversion标识的特征,则返回True

DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)

Return a new Document object (the root of the DOM), with a child Element object having the given namespaceUri and qualifiedName. 返回一个新的Document对象(DOM的根),子Element对象具有给定的namespaceUriqualifiedNameThe doctype must be a DocumentType object created by createDocumentType(), or None. doctype必须是由createDocumentType()None创建的DocumentType对象。In the Python DOM API, the first two arguments can also be None in order to indicate that no Element child is to be created.在Python DOM API中,前两个参数也可以是None,以指示不创建Element子级。

DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)

Return a new DocumentType object that encapsulates the given qualifiedName, publicId, and systemId strings, representing the information contained in an XML document type declaration.返回一个新的DocumentType对象,该对象封装了给定的qualifiedNamepublicIdsystemId字符串,表示XML文档类型声明中包含的信息。

Node Objects对象

All of the components of an XML document are subclasses of Node.XML文档的所有组件都是Node的子类。

Node.nodeType

An integer representing the node type. 表示节点类型的整数。Symbolic constants for the types are on the Node object: ELEMENT_NODE, ATTRIBUTE_NODE, TEXT_NODE, CDATA_SECTION_NODE, ENTITY_NODE, PROCESSING_INSTRUCTION_NODE, COMMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, NOTATION_NODE. 这些类型的符号常量位于Node对象上:ELEMENT_NODEATTRIBUTE_NODETEXT_NODECDATA_SECTION_NODEENTITY_NODEPROCESSING_INSTRUCTION_NODECOMMENT_NODEDOCUMENT_NODEDOCUMENT_TYPE_NODENOTATION_NODEThis is a read-only attribute.这是一个只读属性。

Node.parentNode

The parent of the current node, or None for the document node. 当前节点的父节点,或文档节点的NoneThe value is always a Node object or None. 该值始终为Node对象或NoneFor Element nodes, this will be the parent element, except for the root element, in which case it will be the Document object. 对于Element节点,这将是父元素,根元素除外,在这种情况下,它将是Document对象。For Attr nodes, this is always None. 对于Attr节点,该值始终为NoneThis is a read-only attribute.这是一个只读属性。

Node.attributes

A NamedNodeMap of attribute objects. 属性对象的NamedNodeMapOnly elements have actual values for this; others provide None for this attribute. 只有元素具有此的实际值;其他人对此属性提供NoneThis is a read-only attribute.这是一个只读属性。

Node.previousSibling

The node that immediately precedes this one with the same parent. 紧邻此节点之前的节点具有相同的父节点。For instance the element with an end-tag that comes just before the self element’s start-tag. 例如,带有结束标记的元素正好位于self元素的开始标记之前。Of course, XML documents are made up of more than just elements so the previous sibling could be text, a comment, or something else. 当然,XML文档不仅仅由元素组成,因此前面的同级可以是文本、注释或其他内容。If this node is the first child of the parent, this attribute will be None. 如果该节点是父节点的第一个子节点,则该属性将为NoneThis is a read-only attribute.这是一个只读属性。

Node.nextSibling

The node that immediately follows this one with the same parent. 紧随其后的节点具有相同的父节点。See also previousSibling. 另请参见previousSiblingIf this is the last child of the parent, this attribute will be None. 如果这是父级的最后一个子级,则该属性将为NoneThis is a read-only attribute.这是一个只读属性。

Node.childNodes

A list of nodes contained within this node. 此节点中包含的节点列表。This is a read-only attribute.这是一个只读属性。

Node.firstChild

The first child of the node, if there are any, or None. 节点的第一个子节点(如果有)或NoneThis is a read-only attribute.这是一个只读属性。

Node.lastChild

The last child of the node, if there are any, or None. 节点的最后一个子节点(如果有)或NoneThis is a read-only attribute.这是一个只读属性。

Node.localName

The part of the tagName following the colon if there is one, else the entire tagName. 冒号后面的tagName部分(如果有),否则为整个tagNameThe value is a string.该值是一个字符串。

Node.prefix

The part of the tagName preceding the colon if there is one, else the empty string. tagName中冒号前面的部分(如果有),否则为空字符串。The value is a string, or None.该值为字符串或None

Node.namespaceURI

The namespace associated with the element name. 与元素名称关联的命名空间。This will be a string or None. 这将是字符串或NoneThis is a read-only attribute.这是一个只读属性。

Node.nodeName

This has a different meaning for each node type; see the DOM specification for details. 这对于每个节点类型具有不同的含义;有关详细信息,请参阅DOM规范。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. 您始终可以从另一个属性(例如元素的tagName属性或属性的name属性)获取此处要获取的信息。For all node types, the value of this attribute will be either a string or None. 对于所有节点类型,该属性的值将为字符串或NoneThis is a read-only attribute.这是一个只读属性。

Node.nodeValue

This has a different meaning for each node type; see the DOM specification for details. 这对于每个节点类型具有不同的含义;有关详细信息,请参阅DOM规范。The situation is similar to that with nodeName. 这种情况与nodeName类似。The value is a string or None.该值为字符串或None

Node.hasAttributes()

Return True if the node has any attributes.如果节点有任何属性,则返回True

Node.hasChildNodes()

Return True if the node has any child nodes.如果节点有任何子节点,则返回True

Node.isSameNode(other)

Return True if other refers to the same node as this node. 如果其他节点引用与此节点相同的节点,则返回TrueThis is especially useful for DOM implementations which use any sort of proxy architecture (because more than one object can refer to the same node).这对于使用任何类型的代理架构的DOM实现尤其有用(因为不止一个对象可以引用同一个节点)。

Note

This is based on a proposed DOM Level 3 API which is still in the “working draft” stage, but this particular interface appears uncontroversial. 这是基于一个建议的DOM Level 3 API,该API仍处于“工作草案”阶段,但这个特定的接口似乎没有争议。Changes from the W3C will not necessarily affect this method in the Python DOM interface (though any new W3C API for this would also be supported).W3C的更改不一定会影响Python DOM接口中的此方法(尽管也支持任何新的W3C API)。

Node.appendChild(newChild)

Add a new child node to this node at the end of the list of children, returning newChild. 在子节点列表的末尾向该节点添加一个新的子节点,返回newChildIf the node was already in the tree, it is removed first.如果节点已经在树中,则首先将其删除。

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, ValueError is raised. refChild必须是该节点的子节点;否则,将引发ValueErrornewChild is returned. 返回newChildIf refChild is None, it inserts newChild at the end of the children’s list.如果refChildNone,则在子列表的末尾插入newChild

Node.removeChild(oldChild)

Remove a child node. 删除子节点。oldChild must be a child of this node; if not, ValueError is raised. oldChild必须是此节点的子级;否则,将引发ValueErroroldChild is returned on success. 成功时返回oldChildIf oldChild will not be used further, its unlink() method should be called.如果不再使用oldChild,则应调用其unlink()方法。

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, ValueError is raised.oldChild必须是该节点的子节点;否则,将引发ValueError

Node.normalize()

Join adjacent text nodes so that all stretches of text are stored as single Text instances. 连接相邻的文本节点,以便将所有文本延伸存储为单个Text实例。This simplifies processing text from a DOM tree for many applications.这简化了许多应用程序处理DOM树中的文本。

Node.cloneNode(deep)

Clone this node. 克隆此节点。Setting deep means to clone all child nodes as well. 设置deep也意味着克隆所有子节点。This returns the clone.这将返回克隆。

NodeList Objects对象

A NodeList represents a sequence of nodes. NodeList表示节点序列。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.这些对象在DOM核心建议中有两种使用方式:Element对象提供一个作为其子节点列表,NodegetElementsByTagName()getElementsByTagNameNS()方法使用此接口返回对象以表示查询结果。

The DOM Level 2 recommendation defines one method and one attribute for these objects:DOM级别2建议为这些对象定义了一个方法和一个属性:

NodeList.item(i)

Return the i’th item from the sequence, if there is one, or None. 返回序列中的第i个项目(如果有),或NoneThe index i is not allowed to be less than zero or greater than or equal to the length of the sequence.索引i不允许小于零或大于或等于序列的长度。

NodeList.length

The number of nodes in the sequence.序列中的节点数。

In addition, the Python DOM interface requires that some additional support is provided to allow NodeList objects to be used as Python sequences. 此外,Python DOM接口要求提供一些额外的支持,以允许将NodeList对象用作Python序列。All NodeList implementations must include support for __len__() and __getitem__(); this allows iteration over the NodeList in for statements and proper support for the len() built-in function.所有NodeList实现必须包括对__len__()__getitem__()的支持;这允许在for语句中迭代NodeList,并适当支持len()内置函数。

If a DOM implementation supports modification of the document, the NodeList implementation must also support the __setitem__() and __delitem__() methods.如果DOM实现支持对文档的修改,则NodeList实现还必须支持__setitem__()__delitem__()方法。

DocumentType Objects对象

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. 关于文档声明的符号和实体的信息(包括外部子集,如果解析器使用它并且可以提供信息)可以从DocumentType对象获得。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.文档的DocumentType可从Document对象的doctype属性中获得;如果文档没有DOCTYPE声明,则文档的doctype属性将设置为None,而不是该接口的实例。

DocumentType is a specialization of Node, and adds the following attributes:Node的专用化,并添加了以下属性:

DocumentType.publicId

The public identifier for the external subset of the document type definition. 文档类型定义的外部子集的公共标识符。This will be a string or None.这将是字符串或None

DocumentType.systemId

The system identifier for the external subset of the document type definition. 文档类型定义的外部子集的系统标识符。This will be a URI as a string, or None.这将是一个字符串形式的URI,或None

DocumentType.internalSubset

A string giving the complete internal subset from the document. 给出文档完整内部子集的字符串。This does not include the brackets which enclose the subset. 这不包括包围子集的括号。If the document has no internal subset, this should be None.如果文档没有内部子集,则应为None

DocumentType.name

The name of the root element as given in the DOCTYPE declaration, if present.DOCTYPE声明中给出的根元素的名称(如果存在)。

DocumentType.entities

This is a NamedNodeMap giving the definitions of external entities. 这是一个提供外部实体定义的NamedNodeMapFor entity names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). 对于多次定义的实体名称,只提供第一个定义(根据XML建议,其他定义将被忽略)。This may be None if the information is not provided by the parser, or if no entities are defined.如果解析器未提供信息,或者未定义实体,则该值可能为None

DocumentType.notations

This is a NamedNodeMap giving the definitions of notations. 这是一个NamedNodeMap,给出了符号的定义。For notation names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). 对于多次定义的符号名称,只提供第一个定义(根据XML建议的要求,忽略其他定义)。This may be None if the information is not provided by the parser, or if no notations are defined.如果解析器未提供信息,或者未定义符号,则该值可能为None

Document Objects对象

A Document represents an entire XML document, including its constituent elements, attributes, processing instructions, comments etc. Document表示整个XML文档,包括其组成元素、属性、处理指令、注释等。Remember that it inherits properties from Node.请记住,它从Node继承属性。

Document.documentElement

The one and only root element of the document.文档的唯一根元素。

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().您需要使用其他方法(如insertBefore()appendChild())显式插入它。

Document.createElementNS(namespaceURI, tagName)

Create and return a new element with a namespace. 创建并返回带有命名空间的新元素。The tagName may have a prefix. tagName可能有前缀。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().您需要使用其他方法(如insertBefore()appendChild())显式插入它。

Document.createTextNode(data)

Create and return a text node containing the data passed as a parameter. 创建并返回包含作为参数传递的数据的文本节点。As with the other creation methods, this one does not insert the node into the tree.与其他创建方法一样,此方法不会将节点插入树中。

Document.createComment(data)

Create and return a comment node containing the data passed as a parameter. 创建并返回一个注释节点,其中包含作为参数传递的数据。As with the other creation methods, this one does not insert the node into the tree.与其他创建方法一样,此方法不会将节点插入树中。

Document.createProcessingInstruction(target, data)

Create and return a processing instruction node containing the target and data passed as parameters. 创建并返回包含作为参数传递的targetdata的处理指令节点。As with the other creation methods, this one does not insert the node into the tree.与其他创建方法一样,此方法不会将节点插入树中。

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.必须在适当的Element对象上使用setAttributeNode()才能使用新创建的属性实例。

Document.createAttributeNS(namespaceURI, qualifiedName)

Create and return an attribute node with a namespace. 创建并返回带有命名空间的属性节点。The tagName may have a prefix. tagName可能有前缀。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.必须在适当的Element对象上使用setAttributeNode()才能使用新创建的属性实例。

Document.getElementsByTagName(tagName)

Search for all descendants (direct children, children’s children, etc.) with a particular element type name.搜索具有特定元素类型名称的所有子代(直系子代、子代的子代等)。

Document.getElementsByTagNameNS(namespaceURI, localName)

Search for all descendants (direct children, children’s children, etc.) with a particular namespace URI and localname. 搜索具有特定命名空间URI和本地名称的所有子代(直接子代、子代的子代等)。The localname is the part of the namespace after the prefix.localname是前缀后命名空间的一部分。

Element Objects对象

Element is a subclass of Node, so inherits all the attributes of that class.ElementNode的子类,因此继承该类的所有属性。

Element.tagName

The element type name. 元素类型名称。In a namespace-using document it may have colons in it. 在使用文档的命名空间中,它可能有冒号。The value is a string.该值是一个字符串。

Element.getElementsByTagName(tagName)

Same as equivalent method in the Document class.Document类中的等效方法相同。

Element.getElementsByTagNameNS(namespaceURI, localName)

Same as equivalent method in the Document class.Document类中的等效方法相同。

Element.hasAttribute(name)

Return True if the element has an attribute named by name.如果元素具有按name命名的属性,则返回True。

Element.hasAttributeNS(namespaceURI, localName)

Return True if the element has an attribute named by namespaceURI and localName.如果元素具有由namespaceURIlocalName命名的属性,则返回True

Element.getAttribute(name)

Return the value of the attribute named by name as a string. 以字符串形式返回按name命名的属性的值。If no such attribute exists, an empty string is returned, as if the attribute had no value.如果不存在这样的属性,则返回一个空字符串,就像该属性没有值一样。

Element.getAttributeNode(attrname)

Return the Attr node for the attribute named by attrname.返回由attrname命名的属性的Attr节点。

Element.getAttributeNS(namespaceURI, localName)

Return the value of the attribute named by namespaceURI and localName as a string. 以字符串形式返回由namespaceURIlocalName命名的属性的值。If no such attribute exists, an empty string is returned, as if the attribute had no value.如果不存在这样的属性,则返回一个空字符串,就像该属性没有值一样。

Element.getAttributeNodeNS(namespaceURI, localName)

Return an attribute value as a node, given a namespaceURI and localName.给定namespaceURIlocalName,将属性值作为节点返回。

Element.removeAttribute(name)

Remove an attribute by name. 按名称移除属性。If there is no matching attribute, a NotFoundErr is raised.如果没有匹配的属性,将引发NotFoundErr

Element.removeAttributeNode(oldAttr)

Remove and return oldAttr from the attribute list, if present. 从属性列表中删除并返回oldAttr(如果存在)。If oldAttr is not present, NotFoundErr is raised.如果oldAttr不存在,则引发NotFoundErr

Element.removeAttributeNS(namespaceURI, localName)

Remove an attribute by name. 按名称移除属性。Note that it uses a localName, not a qname. 请注意,它使用的是localName,而不是qname。No exception is raised if there is no matching attribute.如果没有匹配的属性,则不会引发异常。

Element.setAttribute(name, value)

Set an attribute value from a string.从字符串设置属性值。

Element.setAttributeNode(newAttr)

Add a new attribute node to the element, replacing an existing attribute if necessary if the name attribute matches. 向元素添加新的属性节点,如果name属性匹配,则根据需要替换现有属性。If a replacement occurs, the old attribute node will be returned. 如果发生替换,将返回旧属性节点。If newAttr is already in use, InuseAttributeErr will be raised.如果newAttr已在使用中,将引发InuseAttributeErr

Element.setAttributeNodeNS(newAttr)

Add a new attribute node to the element, replacing an existing attribute if necessary if the namespaceURI and localName attributes match. 向元素添加新的属性节点,如果namespaceURIlocalName属性匹配,则在必要时替换现有属性。If a replacement occurs, the old attribute node will be returned. 如果发生替换,将返回旧属性节点。If newAttr is already in use, InuseAttributeErr will be raised.如果newAttr已在使用中,将引发InuseAttributeErr

Element.setAttributeNS(namespaceURI, qname, value)

Set an attribute value from a string, given a namespaceURI and a qname. 给定namespaceURIqname,从字符串中设置属性值。Note that a qname is the whole attribute name. 请注意,qname是整个属性名。This is different than above.这与上面不同。

Attr Objects对象

Attr inherits from Node, so inherits all its attributes.Node继承,因此继承其所有属性。

Attr.name

The attribute name. 属性名称。In a namespace-using document it may include a colon.在使用命名空间的文档中,它可能包含冒号。

Attr.localName

The part of the name following the colon if there is one, else the entire name. 冒号后的部分名称(如果有),否则为整个名称。This is a read-only attribute.这是一个只读属性。

Attr.prefix

The part of the name preceding the colon if there is one, else the empty string.冒号前面的名称部分(如果有),否则为空字符串。

Attr.value

The text value of the attribute. 属性的文本值。This is a synonym for the nodeValue attribute.这是nodeValue属性的同义词。

NamedNodeMap Objects对象

NamedNodeMap does not inherit from Node.Node继承。

NamedNodeMap.length

The length of the attribute list.属性列表的长度。

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. 获取属性的顺序是任意的,但在DOM的生命周期中是一致的。Each item is an attribute node. 每个项目都是一个属性节点。Get its value with the value attribute.使用value属性获取其值。

There are also experimental methods that give this class more mapping behavior. 还有一些实验方法赋予了这个类更多的映射行为。You can use them or you can use the standardized getAttribute*() family of methods on the Element objects.您可以使用它们,也可以在Element对象上使用标准化的getAttribute*()方法族。

Comment Objects对象

Comment represents a comment in the XML document. 表示XML文档中的注释。It is a subclass of Node, but cannot have child nodes.它是Node的子类,但不能有子节点。

Comment.data

The content of the comment as a string. 注释的内容为字符串。The attribute contains all characters between the leading <!-- and trailing -->, but does not include them.该属性包含前导<!--和尾部-->之间的所有字符,但不包括它们。

Text and CDATASection ObjectsText对象和CDATASection对象

The Text interface represents text in the XML document. Text接口表示XML文档中的文本。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. 如果解析器和DOM实现支持DOM的XML扩展,则CDATA标记部分中包含的部分文本将存储在CDATASection对象中。These two interfaces are identical, but provide different values for the nodeType attribute.这两个接口相同,但为nodeType属性提供了不同的值。

These interfaces extend the Node interface. 这些接口扩展了Node接口。They cannot have child nodes.它们不能有子节点。

Text.data

The content of the text node as a string.文本节点的内容作为字符串。

Note

The use of a CDATASection node does not indicate that the node represents a complete CDATA marked section, only that the content of the node was part of a CDATA section. CDATASection节点的使用并不表示该节点表示完整的CDATA标记节,仅表示该节点的内容是CDATA节的一部分。A single CDATA section may be represented by more than one node in the document tree. 单个CDATA节可以由文档树中的多个节点表示。There is no way to determine whether two adjacent CDATASection nodes represent different CDATA marked sections.无法确定两个相邻的CDATASection节点是否表示不同的CDATA标记节。

ProcessingInstruction Objects对象

Represents a processing instruction in the XML document; this inherits from the Node interface and cannot have child nodes.表示XML文档中的处理指令;它继承自Node接口,不能有子节点。

ProcessingInstruction.target

The content of the processing instruction up to the first whitespace character. 直到第一个空白字符的处理指令的内容。This is a read-only attribute.这是一个只读属性。

ProcessingInstruction.data

The content of the processing instruction following the first whitespace character.第一个空白字符后面的处理指令的内容。

Exceptions

The DOM Level 2 recommendation defines a single exception, DOMException, and a number of constants that allow applications to determine what sort of error occurred. DOM Level 2建议定义了一个异常DOMException和许多常量,这些常量允许应用程序确定发生了什么类型的错误。DOMException instances carry a code attribute that provides the appropriate value for the specific exception.实例携带一个code属性,为特定异常提供适当的值。

The Python DOM interface provides the constants, but also expands the set of exceptions so that a specific exception exists for each of the exception codes defined by the DOM. Python DOM接口提供了常量,但也扩展了异常集,以便DOM定义的每个异常代码都存在特定的异常。The implementations must raise the appropriate specific exception, each of which carries the appropriate value for the code attribute.实现必须引发适当的特定异常,每个异常都带有code属性的适当值。

exceptionxml.dom.DOMException

Base exception class used for all specific DOM exceptions. 用于所有特定DOM异常的基本异常类。This exception class cannot be directly instantiated.无法直接实例化此异常类。

exceptionxml.dom.DomstringSizeErr

Raised when a specified range of text does not fit into a string. 当指定的文本范围不适合字符串时引发。This is not known to be used in the Python DOM implementations, but may be received from DOM implementations not written in Python.这不知道在Python DOM实现中使用,但可能从不是用Python的DOM实现接收。

exceptionxml.dom.HierarchyRequestErr

Raised when an attempt is made to insert a node where the node type is not allowed.尝试插入不允许节点类型的节点时引发。

exceptionxml.dom.IndexSizeErr

Raised when an index or size parameter to a method is negative or exceeds the allowed values.当方法的索引或大小参数为负或超过允许值时引发。

exceptionxml.dom.InuseAttributeErr

Raised when an attempt is made to insert an Attr node that is already present elsewhere in the document.尝试插入文档中其他位置已存在的Attr节点时引发。

exceptionxml.dom.InvalidAccessErr

Raised if a parameter or an operation is not supported on the underlying object.如果基础对象不支持参数或操作,则引发。

exceptionxml.dom.InvalidCharacterErr

This exception is raised when a string parameter contains a character that is not permitted in the context it’s being used in by the XML 1.0 recommendation. 当字符串参数包含XML 1.0推荐使用的上下文中不允许的字符时,会引发此异常。For example, attempting to create an Element node with a space in the element type name will cause this error to be raised.例如,尝试创建元素类型名称中有空格的Element节点将导致引发此错误。

exceptionxml.dom.InvalidModificationErr

Raised when an attempt is made to modify the type of a node.尝试修改节点类型时引发。

exceptionxml.dom.InvalidStateErr

Raised when an attempt is made to use an object that is not defined or is no longer usable.尝试使用未定义或不再可用的对象时引发。

exceptionxml.dom.NamespaceErr

If an attempt is made to change any object in a way that is not permitted with regard to the Namespaces in XML recommendation, this exception is raised.如果试图以XML中的命名空间建议不允许的方式更改任何对象,则会引发此异常。

exceptionxml.dom.NotFoundErr

Exception when a node does not exist in the referenced context. 引用上下文中不存在节点时发生异常。For example, NamedNodeMap.removeNamedItem() will raise this if the node passed in does not exist in the map.例如,如果传入的节点在映射中不存在,NamedNodeMap.removeNamedItem()将引发此问题。

exceptionxml.dom.NotSupportedErr

Raised when the implementation does not support the requested type of object or operation.当实现不支持请求的对象或操作类型时引发。

exceptionxml.dom.NoDataAllowedErr

This is raised if data is specified for a node which does not support data.如果为不支持数据的节点指定了数据,则会引发此问题。

exceptionxml.dom.NoModificationAllowedErr

Raised on attempts to modify an object where modifications are not allowed (such as for read-only nodes).在尝试修改不允许修改的对象(例如只读节点)时引发。

exceptionxml.dom.SyntaxErr

Raised when an invalid or illegal string is specified.指定无效或非法字符串时引发。

exceptionxml.dom.WrongDocumentErr

Raised when a node is inserted in a different document than it currently belongs to, and the implementation does not support migrating the node from one document to the other.当节点插入到当前所属的不同文档中,并且实现不支持将节点从一个文档迁移到另一个文档时引发。

The exception codes defined in the DOM recommendation map to the exceptions described above according to this table:根据此表,DOM推荐中定义的异常代码映射到上述异常:

Constant常数

Exception例外

DOMSTRING_SIZE_ERR

DomstringSizeErr

HIERARCHY_REQUEST_ERR

HierarchyRequestErr

INDEX_SIZE_ERR

IndexSizeErr

INUSE_ATTRIBUTE_ERR

InuseAttributeErr

INVALID_ACCESS_ERR

InvalidAccessErr

INVALID_CHARACTER_ERR

InvalidCharacterErr

INVALID_MODIFICATION_ERR

InvalidModificationErr

INVALID_STATE_ERR

InvalidStateErr

NAMESPACE_ERR

NamespaceErr

NOT_FOUND_ERR

NotFoundErr

NOT_SUPPORTED_ERR

NotSupportedErr

NO_DATA_ALLOWED_ERR

NoDataAllowedErr

NO_MODIFICATION_ALLOWED_ERR

NoModificationAllowedErr

SYNTAX_ERR

SyntaxErr

WRONG_DOCUMENT_ERR

WrongDocumentErr

Conformance合规性

This section describes the conformance requirements and relationships between the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for Python.本节描述了Python DOM API、W3C DOM建议和OMG IDL映射之间的一致性要求和关系。

Type Mapping

The IDL types used in the DOM specification are mapped to Python types according to the following table.根据下表,DOM规范中使用的IDL类型映射到Python类型。

IDL Type

Python Type

boolean

bool or int

int

int

long int

int

unsigned int

int

DOMString

str or bytes

null

None

Accessor Methods访问者方法

The mapping from OMG IDL to Python defines accessor functions for IDL attribute declarations in much the way the Java mapping does. 从OMG IDL到Python的映射以Java映射的方式为IDLattribute声明定义访问器函数。Mapping the IDL declarations映射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()). 生成三个访问器函数:someValue的“get”方法(_get_someValue()),anotherValue的“get”和“set”方法(_get_anotherValue()_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.尤其是,映射不要求IDL属性可以作为普通Python属性访问:object.someValue需要工作,可能会引发AttributeError

The Python DOM API, however, does require that normal attribute access work. 然而,Python DOM API确实需要正常的属性访问工作。This means that the typical surrogates generated by Python IDL compilers are not likely to work, and wrapper objects may be needed on the client if the DOM objects are accessed via CORBA. 这意味着Python IDL编译器生成的典型代理不太可能工作,如果通过CORBA访问DOM对象,则可能需要在客户端上使用包装器对象。While this does require some additional consideration for CORBA DOM clients, the implementers with experience using DOM over CORBA from Python do not consider this a problem. 虽然这确实需要对CORBA DOM客户端进行一些额外的考虑,但有使用Python中的DOM over CORBA的经验的实现者并不认为这是一个问题。Attributes that are declared readonly may not restrict write access in all DOM implementations.声明为readonly的属性可能不会限制所有DOM实现中的写入访问。

In the Python DOM API, accessor functions are not required. 在Python DOM API中,不需要访问器函数。If provided, they should take the form defined by the Python IDL mapping, but these methods are considered unnecessary since the attributes are accessible directly from Python. 如果提供了,它们应该采用Python IDL映射定义的形式,但这些方法被认为是不必要的,因为这些属性可以直接从Python中访问。“Set” accessors should never be provided for readonly attributes.不应为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”. IDL定义没有完全体现W3C DOM API的要求,例如某些对象的概念,例如getElementsByTagName()的返回值是“live”。The Python DOM API does not require implementations to enforce such requirements.Python DOM API不需要实现来执行这些要求。