xml.dom
— The 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 DOM级别1根本没有涉及如何实现这一点,而级别2只提供了有限的改进:有一个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. 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 在Python中,每个DOM实现都将提供一个函数getDOMImplementation()
. 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 byW3C对xml.dom.minidom
.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该name要么是众所周知的,要么是DOM实现的模块名称,要么是None
.None
。If it is not如果不是None
, imports the corresponding module and returns aDOMImplementation
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
.ImportError
。The features list must be a sequence of功能列表必须是一系列(feature, version)
pairs which are passed to thehasFeature()
method on availableDOMImplementation
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.但是,您必须这样做的情况非常罕见,因此这种用法尚未被记录下来。
|
|
|
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 DOM级别2还添加了使用Document
and DocumentType
objects using the DOMImplementation
as well.DOMImplementation
创建新的Document
和DocumentType
对象的能力。
-
DOMImplementation.
hasFeature
(feature, version)¶ Return如果实现了由一对字符串feature和version标识的特征,则返回True
if the feature identified by the pair of strings feature and version is implemented.True
。
-
DOMImplementation.
createDocument
(namespaceUri, qualifiedName, doctype)¶ Return a new返回一个新的Document
object (the root of the DOM), with a childElement
object having the given namespaceUri and qualifiedName.Document
对象(DOM的根),子Element
对象具有给定的namespaceUri和qualifiedName。The doctype must be adoctype必须是由DocumentType
object created bycreateDocumentType()
, orNone
.createDocumentType()
或None
创建的DocumentType
对象。In the Python DOM API, the first two arguments can also be在Python DOM API中,前两个参数也可以是None
in order to indicate that noElement
child is to be created.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
对象,该对象封装了给定的qualifiedName、publicId和systemId字符串,表示XML文档类型声明中包含的信息。
Node
Objects对象¶
All of the components of an XML document are subclasses of XML文档的所有组件都是Node
.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_NODE
、ATTRIBUTE_NODE
、TEXT_NODE
、CDATA_SECTION_NODE
、ENTITY_NODE
、PROCESSING_INSTRUCTION_NODE
、COMMENT_NODE
、DOCUMENT_NODE
、DOCUMENT_TYPE_NODE
和NOTATION_NODE
。This is a read-only attribute.这是一个只读属性。
-
Node.
parentNode
¶ The parent of the current node, or当前节点的父节点,或文档节点的None
for the document node.None
。The value is always a该值始终为Node
object orNone
.Node
对象或None
。For对于Element
nodes, this will be the parent element, except for the root element, in which case it will be theDocument
object.Element
节点,这将是父元素,根元素除外,在这种情况下,它将是Document
对象。For对于Attr
nodes, this is alwaysNone
.Attr
节点,该值始终为None
。This is a read-only attribute.这是一个只读属性。
-
Node.
attributes
¶ A属性对象的NamedNodeMap
of attribute objects.NamedNodeMap
。Only elements have actual values for this; others provide只有元素具有此的实际值;其他人对此属性提供None
for this attribute.None
。This 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
.None
。This is a read-only attribute.这是一个只读属性。
-
Node.
nextSibling
¶ The node that immediately follows this one with the same parent.紧随其后的节点具有相同的父节点。See also另请参见previousSibling
.previousSibling
。If this is the last child of the parent, this attribute will be如果这是父级的最后一个子级,则该属性将为None
.None
。This 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
.None
。This is a read-only attribute.这是一个只读属性。
-
Node.
lastChild
¶ The last child of the node, if there are any, or节点的最后一个子节点(如果有)或None
.None
。This is a read-only attribute.这是一个只读属性。
-
Node.
localName
¶ The part of the冒号后面的tagName
following the colon if there is one, else the entiretagName
.tagName
部分(如果有),否则为整个tagName
。The value is a string.该值是一个字符串。
-
Node.
prefix
¶ The part of thetagName
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
.None
。This 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 thename
property for attributes.tagName
属性或属性的name
属性)获取此处要获取的信息。For all node types, the value of this attribute will be either a string or对于所有节点类型,该属性的值将为字符串或None
.None
。This 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.True
。This 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.在子节点列表的末尾向该节点添加一个新的子节点,返回newChild。If 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,refChild必须是该节点的子节点;否则,将引发ValueError
is raised.ValueError
。newChild is returned.返回newChild。If refChild is如果refChild为None
, it inserts newChild at the end of the children’s list.None
,则在子列表的末尾插入newChild。
-
Node.
removeChild
(oldChild)¶ Remove a child node.删除子节点。oldChild must be a child of this node; if not,oldChild必须是此节点的子级;否则,将引发ValueError
is raised.ValueError
。oldChild is returned on success.成功时返回oldChild。If oldChild will not be used further, its如果不再使用oldChild,则应调用其unlink()
method should be called.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,oldChild必须是该节点的子节点;否则,将引发ValueError
is raised.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 这些对象在DOM核心建议中有两种使用方式: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.Element
对象提供一个作为其子节点列表,Node
的getElementsByTagName()
和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返回序列中的第i个项目(如果有),或None
.None
。The 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 此外,Python DOM接口要求提供一些额外的支持,以允许将NodeList
objects to be used as Python sequences. 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 如果DOM实现支持对文档的修改,则NodeList
implementation must also support the __setitem__()
and __delitem__()
methods.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这将是一个字符串形式的URI,或None
.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 theDOCTYPE
declaration, if present.DOCTYPE
声明中给出的根元素的名称(如果存在)。
-
DocumentType.
entities
¶ This is a这是一个提供外部实体定义的NamedNodeMap
giving the definitions of external entities.NamedNodeMap
。For 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()
orappendChild()
.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()
orappendChild()
.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.创建并返回包含作为参数传递的target和data的处理指令节点。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 appropriateElement
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 appropriateElement
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.Element
是Node
的子类,因此继承该类的所有属性。
-
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如果元素具有按name命名的属性,则返回True。True
if the element has an attribute named by name.
-
Element.
hasAttributeNS
(namespaceURI, localName)¶ Return如果元素具有由namespaceURI和localName命名的属性,则返回True
if the element has an attribute named by namespaceURI and localName.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返回由attrname命名的属性的Attr
node for the attribute named by attrname.Attr
节点。
-
Element.
getAttributeNS
(namespaceURI, localName)¶ Return the value of the attribute named by namespaceURI and localName as a string.以字符串形式返回由namespaceURI和localName命名的属性的值。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.给定namespaceURI和localName,将属性值作为节点返回。
-
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,如果oldAttr不存在,则引发NotFoundErr
is raised.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,如果newAttr已在使用中,将引发InuseAttributeErr
will be raised.InuseAttributeErr
。
-
Element.
setAttributeNodeNS
(newAttr)¶ Add a new attribute node to the element, replacing an existing attribute if necessary if the向元素添加新的属性节点,如果namespaceURI
andlocalName
attributes match.namespaceURI
和localName
属性匹配,则在必要时替换现有属性。If a replacement occurs, the old attribute node will be returned.如果发生替换,将返回旧属性节点。If newAttr is already in use,如果newAttr已在使用中,将引发InuseAttributeErr
will be raised.InuseAttributeErr
。
-
Element.
setAttributeNS
(namespaceURI, qname, value)¶ Set an attribute value from a string, given a namespaceURI and a qname.给定namespaceURI和qname,从字符串中设置属性值。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*()
方法族。
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 如果解析器和DOM实现支持DOM的XML扩展,则CDATA标记部分中包含的部分文本将存储在CDATASection
objects. 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 表示XML文档中的处理指令;它继承自Node
interface and cannot have child nodes.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, DOM Level 2建议定义了一个异常DOMException
, and a number of constants that allow applications to determine what sort of error occurred. 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
属性的适当值。
-
exception
xml.dom.
DOMException
¶ Base exception class used for all specific DOM exceptions.用于所有特定DOM异常的基本异常类。This exception class cannot be directly instantiated.无法直接实例化此异常类。
-
exception
xml.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实现接收。
-
exception
xml.dom.
HierarchyRequestErr
¶ Raised when an attempt is made to insert a node where the node type is not allowed.尝试插入不允许节点类型的节点时引发。
-
exception
xml.dom.
IndexSizeErr
¶ Raised when an index or size parameter to a method is negative or exceeds the allowed values.当方法的索引或大小参数为负或超过允许值时引发。
-
exception
xml.dom.
InuseAttributeErr
¶ Raised when an attempt is made to insert an尝试插入文档中其他位置已存在的Attr
node that is already present elsewhere in the document.Attr
节点时引发。
-
exception
xml.dom.
InvalidAccessErr
¶ Raised if a parameter or an operation is not supported on the underlying object.如果基础对象不支持参数或操作,则引发。
-
exception
xml.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
节点将导致引发此错误。
-
exception
xml.dom.
InvalidModificationErr
¶ Raised when an attempt is made to modify the type of a node.尝试修改节点类型时引发。
-
exception
xml.dom.
InvalidStateErr
¶ Raised when an attempt is made to use an object that is not defined or is no longer usable.尝试使用未定义或不再可用的对象时引发。
-
exception
xml.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中的命名空间建议不允许的方式更改任何对象,则会引发此异常。
-
exception
xml.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()
将引发此问题。
-
exception
xml.dom.
NotSupportedErr
¶ Raised when the implementation does not support the requested type of object or operation.当实现不支持请求的对象或操作类型时引发。
-
exception
xml.dom.
NoDataAllowedErr
¶ This is raised if data is specified for a node which does not support data.如果为不支持数据的节点指定了数据,则会引发此问题。
-
exception
xml.dom.
NoModificationAllowedErr
¶ Raised on attempts to modify an object where modifications are not allowed (such as for read-only nodes).在尝试修改不允许修改的对象(例如只读节点)时引发。
-
exception
xml.dom.
SyntaxErr
¶ Raised when an invalid or illegal string is specified.指定无效或非法字符串时引发。
-
exception
xml.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推荐中定义的异常代码映射到上述异常:
|
|
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Accessor Methods访问者方法¶
The mapping from OMG IDL to Python defines accessor functions for IDL 从OMG IDL到Python的映射以Java映射的方式为IDLattribute
declarations in much the way the Java mapping does. attribute
声明定义访问器函数。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: 尤其是,映射不要求IDL属性可以作为普通Python属性访问:object.someValue
is not required to work, and may raise an AttributeError
.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 IDL定义没有完全体现W3C DOM API的要求,例如某些对象的概念,例如getElementsByTagName()
, being “live”. getElementsByTagName()
的返回值是“live”。The Python DOM API does not require implementations to enforce such requirements.Python DOM API不需要实现来执行这些要求。
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.<!--
和尾部-->
之间的所有字符,但不包括它们。