xml.dom — The Document Object Model API¶
Código Fuente: Lib/xml/dom/__init__.py
El Modelo de Objetos del Documento, o «DOM» por sus siglas en inglés, es un lenguaje API del Consorcio World Wide Web (W3C) para acceder y modificar documentos XML. Una implementación del DOM presenta los documento XML como un árbol, o permite al código cliente construir dichas estructuras desde cero para luego darles acceso a la estructura a través de un conjunto de objetos que implementaron interfaces conocidas.
El DOM es extremadamente útil para aplicaciones de acceso directo. SAX sólo te permite la vista de una parte del documento a la vez. Si estás mirando un elemento SAX, no tienes acceso a otro. Si estás viendo un nodo de texto, no tienes acceso al elemento contenedor. Cuando desarrollas una aplicación SAX, necesitas registrar la posición de tu programa en el documento en algún lado de tu código. SAX no lo hace por ti. Además, desafortunadamente no podrás mirar hacia adelante (look ahead) en el documento XML.
Algunas aplicaciones son imposibles en un modelo orientado a eventos sin acceso a un árbol. Por supuesto que puedes construir algún tipo de árbol por tu cuenta en eventos SAX, pero el DOM te evita escribir ese código. El DOM es una representación de árbol estándar para datos XML.
El Modelo de Objetos del Documento es definido por el W3C en fases, o «niveles» en su terminología. El mapeado de Python de la API está basado en la recomendación del DOM nivel 2.
Las aplicaciones DOM típicamente empiezan al diseccionar (parse) el XML en un DOM. Cómo esto funciona no está incluido en el DOM nivel 1, y el nivel 2 provee mejoras limitadas. Existe una clase objeto llamada DOMImplementation que da acceso a métodos de creación de Document, pero de ninguna forma da acceso a los constructores (builders) de reader/parser/Document de una forma independiente a la implementación. No hay una forma clara para acceder a estos método sin un objeto Document existente. En Python, cada implementación del DOM proporcionará una función getDOMImplementation(). El DOM de nivel 3 añade una especificación para Cargar(Load)/Guardar(Store), que define una interfaz al lector (reader), pero no está disponible aún en la librería estándar de Python.
Una vez que tengas un objeto del documento del DOM, puedes acceder a las partes de tu documento XML a través de sus propiedades y métodos. Estas propiedades están definidas en la especificación del DOM; está porción del manual describe la interpretación de la especificación en Python.
La especificación estipulada por el W3C define la DOM API para Java, ECMAScript, y OMG IDL. El mapeo de Python definido aquí está basado en gran parte en la versión IDL de la especificación, pero no se requiere el cumplimiento estricto (aunque las implementaciones son libres de soportar el mapeo estricto de IDL). Véase la sección Conformidad para una discusión detallada del mapeo de los requisitos.
Ver también
- Document Object Model (DOM) Level 2 Specification
La recomendación del W3C con la cual se basa el DOM API de Python.
- Document Object Model (DOM) Level 1 Specification
La recomendación del W3C para el DOM soportada por
xml.dom.minidom.- Python Language Mapping Specification
Este documento especifica el mapeo de OMG IDL a Python.
Contenido del módulo¶
The xml.dom contains the following functions:
- xml.dom.registerDOMImplementation(name, factory)¶
Registra la función factory con el nombre name. La función fábrica (factory) debe retornar un objeto que implemente la interfaz
DOMImplementation. La función fábrica puede retornar el mismo objeto cada vez que se llame, o uno nuevo por cada llamada, según sea apropiado para la implementación específica (e.g. si la implementación soporta algunas personalizaciones).
- 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 notNone, imports the corresponding module and returns aDOMImplementationobject if the import succeeds. If no name is given, and if the environment variablePYTHON_DOMis set, this variable is used to find the implementation. The only well-known name in the standard library is'minidom', forxml.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 thehasFeature()method on availableDOMImplementationobjects.
Algunas constantes convenientes son proporcionadas:
- 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
namespaceURIof a node, or used as the namespaceURI parameter to a namespaces-specific method.
- xml.dom.XML_NAMESPACE¶
El espacio de nombres de la URI asociada con el prefijo
xml, como se define por Namespaces in XML (sección 4).
- xml.dom.XMLNS_NAMESPACE¶
El espacio de nombres del URI para declaraciones del espacio de nombres, como se define en Document Object Model (DOM) Level 2 Core Specification (sección 1.1.8).
- xml.dom.XHTML_NAMESPACE¶
El URI del espacio de nombres del XHTML como se define en XHTML 1.0: The Extensible HyperText Markup Language (sección 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.
Objetos en el DOM¶
La documentación definitiva para el DOM es la especificación del DOM del W3C.
Note que los atributos del DOM también pueden ser manipulados como nodos en vez de simples cadenas de caracteres (strings). Sin embargo, es bastante raro que tengas que hacer esto, por lo que su uso aún no está documentado.
Interfaz |
Sección |
Propósito |
|---|---|---|
Interfaz para las implementaciones subyacentes. |
||
Interfaz base para la mayoría de objetos en un documento. |
||
Interfaz para una secuencia de nodos. |
||
Información acerca de la declaraciones necesarias para procesar un documento. |
||
Objeto que representa un documento entero. |
||
Nodos elemento en la jerarquía del documento. |
||
Nodos de los valores de los atributos en los elementos nodo. |
||
Representación de los comentarios en el documento fuente. |
||
Nodos con contenido textual del documento. |
||
Representación de instrucción del procesamiento. |
Una sección adicional describe las excepciones definidas para trabajar con el DOM en Python.
Objetos DOMImplementation¶
La interfaz DOMImplementation proporciona una forma para que las aplicaciones determinen la disponibilidad de características particulares en el DOM que están usando. El DOM nivel 2 añadió la habilidad de crear nuevos objetos Document y DocumentType usando DOMImplementation también.
- DOMImplementation.hasFeature(feature, version)¶
Retorna
Truesi la característica identificada por el par de cadenas de caracteres feature y version está implementada.
- DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)¶
Retorna un nuevo objeto
Document(la raíz del DOM), con un hijo objetoElementteniendo el namespaceUri y qualifiedName dados. El doctype debe ser unDocumentTypecreado porcreateDocumentType()oNone. En la DOM API de Python, los primeros argumentos pueden serNonepara indicar que ningún hijoElementva a ser creado.
- DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)¶
Retorna un nuevo objeto
DocumentTypeque encapsula las cadenas de caracteres qualifiedName, publicId, y systemId dadas, representando la información contenida en un tipo de declaración de documento XML.
Objetos nodo¶
Todos los componentes de un documento XML son sub-clases de Node.
Only nodes of the following types can have children, and only children of the listed types:
Documentat most one
Element, at most oneDocumentType,ProcessingInstructionandCommentDocumentFragmentandElementElement,Text,CDATASection,ProcessingInstructionandCommentAttr
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
Nodeobject. 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
nodeTypeattribute.
- Node.parentNode¶
El padre del nodo actual, o
Nonepara el nodo del documento. El valor es siempre un objetoNodeoNone. Para los nodosElement, este será el elemento padre, excepto para el elemento raíz, en cuyo caso será el objetoDocument. Para los nodosAttr, este siempre esNone. Este es un atributo de sólo lectura.
- Node.attributes¶
Un
NamedNodeMapde objetos de atributos. Sólo los elementos tienes un valor real para esto; otros nodos proporcionanNonepara este atributo. Este es un atributo de sólo lectura.
- Node.previousSibling¶
El nodo que precede inmediatamente este nodo con el mismo padre. Por ejemplo el elemento con una etiqueta final que viene justo antes de la etiqueta del comienzo del elemento self. Por supuesto, los documentos XML está hechos de más que sólo elementos por lo que el hermano anterior puede ser un texto, un comentario, o algo más. Si este nodo es el primer hijo del padre, este atributo será
None. Este es un atributo de sólo lectura.
- Node.nextSibling¶
El nodo que sigue inmediatamente este nodo con el mismo padre. Véase también
previousSibling. Si este es el último hijo del padre, este atributo seráNone. Este es un atributo de sólo lectura.
- Node.childNodes¶
A
NodeListof the children of this node. If the node has no children, the list is empty. This is a read-only attribute.
- Node.firstChild¶
El primer hijo del nodo, si hay alguno, o
None. Este es un atributo de sólo lectura.
- Node.lastChild¶
El último hijo del nodo, si hay alguno, o
None. Este es un atributo de sólo lectura.
- Node.localName¶
The part of the
tagNamefollowing the colon if there is one, else the entiretagName. The value is a string.
- Node.prefix¶
The part of the
tagNamepreceding the colon if there is one, else the empty string. The value is a string, orNone.
- Node.namespaceURI¶
El espacio de nombres asociado con el nombre del elemento. Este será una cadena de caracteres o
None. Este es una atributo de sólo lectura.
- Node.ownerDocument¶
The
Documentobject to which this node belongs, orNonefor 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 isNone, the association is removed. handler is called when the node is cloned, imported, renamed or deleted; passNoneif no notification is needed.
- Node.getUserData(key)¶
Return the data associated with key on this node by
setUserData(), orNone.
- 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
tagNameproperty for elements or thenameproperty 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 |
|---|---|---|
|
the content |
|
|
the content |
|
|
|
|
|
|
|
|
||
|
||
the name of the entity |
|
|
the name of the notation |
|
|
|
the content |
- Node.hasAttributes()¶
Retorna
Truesi el nodo tiene algún atributo.
- Node.hasChildNodes()¶
Retorna
Truesi el nodo tiene algún nodo hijo.
- Node.isSameNode(other)¶
Retorna
Truesi other hace referencia al mismo nodo como este nodo. Esto es especialmente útil para las implementaciones DOM que usan una arquitectura proxy de cualquier tipo (porque más de un objeto puede hacer referencia al mismo nodo).Nota
Esto se basa en una DOM API de nivel 3 propuesta que está en la etapa de «borrador de trabajo» («working draft»), pero esta interfaz en particular no parece controversial. Los cambios del W3C necesariamente no afectaran este método en la interfaz del DOM del Python (aunque cualquier nueva API del W3C para esto también sería soportado).
- Node.appendChild(newChild)¶
Añade un nuevo nodo hijo a este nodo al final de la lista de hijos, retornando newChild. Si el nodo ya estaba en el árbol, este se remueve primero.
- Node.insertBefore(newChild, refChild)¶
Inserta un nuevo nodo hijo antes de un hijo existente. Debe ser el caso que refChild sea un hijo de este nodo; si no,
ValueErrores lanzado. newChild es retornado. Si refChild esNone, se inserta a newChild al final de la lista de hijos.
- Node.removeChild(oldChild)¶
Remove a child node. oldChild must be a child of this node; if not,
ValueErroris raised. oldChild is returned on success. If oldChild will not be used further, itsunlink()method should be called.
- Node.replaceChild(newChild, oldChild)¶
Reemplaza un nodo existente con un nuevo nodo. Debe ser el caso que oldChild sea un hijo de este nodo; si no,
ValueErrores lanzado.
- Node.normalize()¶
Une nodos de texto adyacentes para que todos los tramos de texto sean guardados como únicas instancias de
Text. Esto simplifica el procesamiento de texto de un árbol del DOM para muchas aplicaciones.
- Node.cloneNode(deep)¶
Clona este nodo. Poner deep significa clonar todos los nodos hijo también. Esto retorna el clon.
Objetos NodeList¶
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.
La recomendación del DOM nivel 2 define un método y un atributo para estos objetos:
- NodeList.item(i)¶
Return the i’th item from the sequence, or
Noneif i is out of range. Negative indices are not supported.
- NodeList.length¶
El número de nodos en la secuencia.
Además, la interfaz DOM de Python requiere que un algún soporte adicional sea proporcionado para que los objetos NodeList puedan ser usados como secuencias de Python. Todas las implementaciones de NodeList deben incluir soporte para __len__() y __getitem__(); esto permite la iteración de NodeList en sentencias con for y un soporte apropiado para la función incorporada len().
Si una implementación DOM soporta la modificación del documento, la implementación de NodeList debe también soportar los métodos __setitem__() y __delitem__().
Objetos DocumentType¶
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.
DocumentType es una especialización de Node, y añade los siguientes atributos:
- DocumentType.publicId¶
The public identifier for the external subset of the document type definition, or
Noneif theDOCTYPEdeclaration does not specify it.
- DocumentType.systemId¶
The system identifier, a URI, for the external subset of the document type definition, or
Noneif theDOCTYPEdeclaration does not specify it.
- DocumentType.internalSubset¶
Una cadena de caracteres proporcionando el subconjunto interno completo del documento. Esto no incluye los paréntesis que cierran el subconjunto. Si el documento no tiene ningún subconjunto interno, debe ser
None.
- DocumentType.name¶
El nombre del elemento raíz como se indica en la declaración
DOCTYPE, si está presente.
- DocumentType.entities¶
This is a
NamedNodeMapofEntitynodes 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 beNoneif the information is not provided by the parser, or if no entities are defined.
- DocumentType.notations¶
This is a
NamedNodeMapofNotationnodes 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 beNoneif the information is not provided by the parser, or if no notations are defined.
Objetos documento¶
Un Documento representa un documento XML entero, incluyendo sus elementos constituyentes, atributos, instrucciones de procesamiento, comentarios, etc. Recuerda que este hereda propiedades de Node.
- Document.documentElement¶
El único elemento raíz del documento.
- Document.doctype¶
The
DocumentTypenode of the document, orNone. This is a read-only attribute.
- Document.implementation¶
The
DOMImplementationobject 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
Noneif it is unknown.
- Document.createDocumentFragment()¶
Create and return an empty
DocumentFragmentnode.
- Document.createCDATASection(data)¶
Create and return a
CDATASectionnode 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()orappendChild().
- 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()orappendChild().
- Document.createTextNode(data)¶
Crea y retorna un nodo texto conteniendo los datos pasados como parámetros, Como con los otros métodos de creación, este no inserta el nodo en el árbol.
- Document.createComment(data)¶
Crea y retorna un nodo comentario conteniendo los datos pasados como parámetros. Como con los otros métodos de creación, este no inserta el nodo en el árbol.
- Document.createProcessingInstruction(target, data)¶
Crea y retorna una instrucción de procesamiento conteniendo el target y data pasados como parámetros. Como con los otros métodos de creación, este no inserta en nodo en el árbol.
- 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 appropriateElementobject 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 appropriateElementobject 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 byElement.setIdAttribute()are searched.
- Document.getElementsByTagName(tagName)¶
Busca todos los descendientes (hijos directos, hijos de los hijos, etc.) con un nombre del tipo de elemento particular.
- Document.getElementsByTagNameNS(namespaceURI, localName)¶
Busca todos los descendientes (hijos directos, hijos de hijos, etc.) con un espacio de nombres URI particular (namespaceURI) y nombre local (localname). El nombre local es parte del espacio de nombres después del prefijo.
- Document.renameNode(n, namespaceURI, name)¶
Rename the element or attribute node n and return it. namespaceURI is the new namespace URI, or
EMPTY_NAMESPACEif the node does not belong to a namespace. name is the new qualified name.Raise
WrongDocumentErrif n was created by another document, andNotSupportedErrif it is neither an element nor an attribute.
Objetos elemento¶
Element es una subclase de Node, por lo que hereda todos los atributos de esa clase.
- Element.tagName¶
El nombre del tipo de elemento. En un documento que usa espacios de nombres este puede tener varios dos puntos en el. El valor es una cadena de caracteres.
- Element.setIdAttribute(name)¶
Declare that the attribute name is of type ID, so that the element is found by
Document.getElementById(). RaiseNotFoundErrif 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.getElementsByTagNameNS(namespaceURI, localName)¶
Igual al método equivalente en la clase
Document.
- Element.hasAttribute(name)¶
Retorna
Truesi el elemento tiene un atributo nombrado name.
- Element.hasAttributeNS(namespaceURI, localName)¶
Retorna
Truesi el elemento tiene un atributo nombrado por namespaceURI y localName.
- Element.getAttribute(name)¶
Retorna el valor del atributo nombrado por name como una cadena de caracteres. Si no existe dicho atributo, una cadena vacía es retornada, como si el atributo no tuviera valor.
- Element.getAttributeNS(namespaceURI, localName)¶
Retorna el valor del atributo nombrado por namespaceURI y localName como una cadena de caracteres. Si no existe dicho atributo, una cadena vacía es retornada, como si el atributo no tuviera valor.
- Element.getAttributeNodeNS(namespaceURI, localName)¶
Retorna un valor de atributo como nodo, dado un namespaceURI y localName.
- Element.removeAttribute(name)¶
Remueve un atributo por nombre (name). Si no hay un atributo correspondiente, un
NotFoundErres lanzado.
- Element.removeAttributeNode(oldAttr)¶
Remueve y retorna oldAttr de la lista de atributos, si está presenta. Si oldAttr no está presente,
NotFoundErres lanzado.
- Element.removeAttributeNS(namespaceURI, localName)¶
Remueve un atributo por nombre (name). Note que esto usa un localName, no un qname. Ninguna excepción es lanzada si no existe el atributo correspondiente.
- Element.setAttribute(name, value)¶
Pone un valor de atributo como una cadena de caracteres.
- Element.setAttributeNode(newAttr)¶
Add a new attribute node to the element, replacing an existing attribute if necessary if the
nameattribute matches. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use,InuseAttributeErrwill be raised.
- Element.setAttributeNodeNS(newAttr)¶
Add a new attribute node to the element, replacing an existing attribute if necessary if the
namespaceURIandlocalNameattributes match. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use,InuseAttributeErrwill be raised.
- Element.setAttributeNS(namespaceURI, qname, value)¶
Pone un valor de atributo a partir de una cadena de caracteres, dados un namespaceURI y qname. Note que un qname es el nombre completo del atributo. Esto es diferente al de arriba.
Objetos atributo¶
Attr hereda de Node, por lo que hereda todos sus atributos.
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¶
El nombre del atributo. En un documento que usa espacio de nombres, puede incluir dos puntos.
- Attr.localName¶
La parte del nombre seguido después de los dos puntos si hay uno, si no el nombre entero. Este es un atributo de sólo lectura.
- Attr.prefix¶
La parte del nombre que precede los dos puntos si hay uno, si no la cadena de caracteres vacía.
- 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
Elementnode to which this attribute belongs, orNoneif 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.
Objetos NamedNodeMap¶
NamedNodeMap no hereda de Node.
- NamedNodeMap.length¶
La longitud de la lista de atributos.
- 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
valueattribute.
- NamedNodeMap.getNamedItem(name)¶
Return the node with the given
name, orNoneif there is no such node.
- NamedNodeMap.getNamedItemNS(namespaceURI, localName)¶
Return the node with the given namespace URI and local name, or
Noneif there is no such node.
- NamedNodeMap.setNamedItem(node)¶
Add node to the map, using its
nameas the key. Return the node which it replaces, orNoneif 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
Noneif it replaces no node.
- NamedNodeMap.removeNamedItem(name)¶
Remove and return the node with the given
name. RaiseNotFoundErrif there is no such node.
- NamedNodeMap.removeNamedItemNS(namespaceURI, localName)¶
Remove and return the node with the given namespace URI and local name. Raise
NotFoundErrif 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.
Objetos Texto y 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¶
El contenido del nodo texto como una cadena de caracteres.
- Text.wholeText¶
The text of all
Textnodes logically adjacent to this node, concatenated in document order. This is a read-only attribute.
- Text.replaceWholeText(content)¶
Replace the text of all
Textnodes logically adjacent to this node with content, removing the other nodes. Return this node, orNoneif 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.
Nota
El uso de un nodo CDATASection no indica que el nodo represente una sección completa marcada como CDATA, sólo que el contenido del nodo fue parte de una sección CDATA. Una sola sección CDATA puede ser representada por más de un nodo en el árbol del documento. No hay manera de determinar si dos nodos adyacentes CDATASection son representados diferentes a secciones marcadas como CDATA.
Objetos ProcessingInstruction¶
Representa una instrucción de procesamiento en el documento XML; hereda de la interfaz Node y no puede tener hijos.
- ProcessingInstruction.target¶
El contenido de la instrucción de procesamiento hasta el carácter en blanco. Este es un atributo de sólo lectura.
- ProcessingInstruction.data¶
El contenido de la instrucción de procesamiento después del primer carácter en blanco.
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
Noneif it is not specified. This is a read-only attribute.
- Entity.systemId¶
The system identifier of the entity, or
Noneif it is not specified. This is a read-only attribute.
- Entity.notationName¶
The name of the notation for an unparsed entity, or
Nonefor 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
Noneif it is not specified. This is a read-only attribute.
- Notation.systemId¶
The system identifier of the notation, or
Noneif it is not specified. This is a read-only attribute.
Excepciones¶
La recomendación del DOM nivel 2 define una sola excepción, DOMException, y un número de constantes que permite que las aplicaciones determinen qué tipo de error ocurrió. las instancias de DOMException llevan un atributo code que proporciona el valor apropiado para la excepción específica.
La interfaz DOM de Python provee las constantes, pero también expande el conjunto de excepciones para que exista una excepción específica para cada uno de los códigos de excepción definidos por el DOM. Las implementaciones deben lanzar la excepción específica apropiada, cada uno de los cuales lleva el valor apropiado para el atributo code.
- exception xml.dom.DOMException¶
Clase base de excepción usada para todas las excepciones del DOM específicas. Esta clase de excepción no puede ser instanciada directamente.
- exception xml.dom.DomstringSizeErr¶
Lanzado cuando un rango de texto específico no cabe en una cadena de caracteres. No se sabe si se usa in las implementación DOM de Python, pero puede ser recibido de otras implementaciones DOM que no hayan sido escritas en Python.
- exception xml.dom.HierarchyRequestErr¶
Lanzado cuando se intenta insertar un nodo donde el tipo de nodo no es permitido.
- exception xml.dom.IndexSizeErr¶
Lanzado cuando un parámetro del índice o tamaño de un método es negativo o excede los valores permitidos.
- exception xml.dom.InuseAttributeErr¶
Lanzado cuando se intenta insertar un nodo
Attrque está presente en algún lado en el documento.
- exception xml.dom.InvalidAccessErr¶
Lanzado si un parámetro o una operación no es soportada por el objeto subyacente.
- exception xml.dom.InvalidCharacterErr¶
Esta excepción es lanzada cuando un parámetro de cadena de caracteres contiene un carácter que no está permitido en el contexto que está siendo usado por la recomendación XML 1.0. Por ejemplo, intentar crear un nodo
Elementcon un espacio en el nombre del tipo de elemento causará que se lance este error.
- exception xml.dom.InvalidModificationErr¶
Lanzado cuando se intenta modificar el tipo de un nodo.
- exception xml.dom.InvalidStateErr¶
Lanzado cuando se intenta usar un objeto que no está definido o ya no es usable.
- exception xml.dom.NamespaceErr¶
Si se intenta cambiar cualquier objeto de forma que no sea permitida con respecto a la recomendación Namespaces in XML, esta excepción es lanzada.
- exception xml.dom.NotFoundErr¶
Excepción cuando un nodo no existe en el contexto referenciado. Por ejemplo,
NamedNodeMap.removeNamedItem()será lanzado si el nodo pasado no existe en el mapa.
- exception xml.dom.NotSupportedErr¶
Lanzado cuando la implementación no soporta el tipo requerido del objeto u operación.
- exception xml.dom.NoDataAllowedErr¶
Es lanzado si se especifican datos para un nodo que no soporta datos.
- exception xml.dom.NoModificationAllowedErr¶
Lanzado cuando se intenta modificar un objeto donde las modificaciones no son permitidas (tal como los nodos de sólo-lectura).
- exception xml.dom.SyntaxErr¶
Lanzado cuando se especifica una cadena de caracteres inválida o ilegal.
- 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¶
Lanzado cuando un nodo es insertado en un documento diferente al que este actualmente pertenece, y la implementación no soporta migrar el nodo de un documento a otro.
Los códigos de excepción definidos en la recomendación del DOM se mapean a las excepciones descritas arriba de acuerdo a esta tabla:
Constante |
Excepción |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Conformidad¶
Esta sección describe los requisitos de conformidad y las relaciones entre el DOM API de Python, las recomendaciones del DOM del W3C, y el mapeo OMG IDL para Python.
Mapeo de tipos¶
Los tipos IDL usados en la especificación del DOM son mapeados a los tipos de tipos de Python de acuerdo a la siguiente tabla.
Tipo IDL |
Tipo en Python |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Métodos de acceso (accessor)¶
El mapeo de OMG IDL a python define funciones de acceso para las declaraciones del atributo IDL de la que misma forma en que el mapeo de Java lo hace. Mapear las declaraciones 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.
El DOM API de Python, sin embargo, si requiere que los atributos de acceso normales funcionen. Esto significa que no es probable que los típicos sustitutos generados por compiladores de IDL en Python funcionen, y los objetos envoltorio (wrapper) pueden ser necesarios en el cliente si los objetos del DOM son accedidos mediante CORBA. Mientras que esto requiere consideraciones adicionales para clientes DOM en CORBA, los implementadores con experiencia que usen DOM por encima de CORBA desde Python no lo consideran un problema. Los atributos que se declaran readonly pueden no restringir el acceso de escritura en todas las implementaciones DOM.
En el DOM API de Python, las funciones de acceso no son obligatorias. Si se proveen, deben tomar la forma definida por el mapeo IDL de Python, pero estos métodos se consideran innecesarios debido a que los atributos son accesibles directamente desde Python. Nunca se deben proporcionar métodos de acceso (accessor) «Set» para los atributos readonly.
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.
Objetos comentario¶
Commentrepresents a comment in the XML document. It is a subclass ofCharacterData.El contenido del comentario como una cadena de caracteres. El atributo contiene todos los caracteres entre el
<!--que empieza y el-->que termina, pero no los incluye.