:mod:`xml.dom` --- The Document Object Model API
The Document Object Model, or "DOM," is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents. A DOM implementation presents an XML document as a tree structure, or allows client code to build such a structure from scratch. 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. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another. 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 does not do it for you. Also, if you need to look ahead in the XML document, you are just out of luck.
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. The DOM is a standard tree representation for XML data.
The Document Object Model is being defined by the W3C in stages, or "levels" in their terminology. The Python mapping of the API is substantially based on the DOM Level 2 recommendation.
DOM applications typically start by parsing some XML into a DOM. How this is accomplished is not covered at all by DOM Level 1, and Level 2 provides only limited improvements: There is a :class:`DOMImplementation` object class which provides access to :class:`Document` creation methods, but no way to access an XML reader/parser/Document builder in an implementation-independent way. There is also no well-defined way to access these methods without an existing :class:`Document` object. In Python, each DOM implementation will provide a function :func:`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.
Once you have a DOM document object, you can access the parts of your XML document through its properties and methods. These properties are defined in the DOM specification; this portion of the reference manual describes the interpretation of the specification in Python.
The specification provided by the W3C defines the DOM API for Java, ECMAScript, and OMG IDL. 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). See section :ref:`dom-conformance` for a detailed discussion of mapping requirements.
The :mod:`xml.dom` contains the following functions:
Some convenience constants are also provided:
In addition, :mod:`xml.dom` contains a base :class:`Node` class and the DOM exception classes. The :class:`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 :class:`Node` class provided as part of this module does provide the constants used for the :attr:`nodeType` attribute on concrete :class:`Node` objects; they are located within the class rather than at the module level to conform with the DOM specifications.
Objects in the DOM
The definitive documentation for the DOM is the DOM specification from the W3C.
Note that DOM attributes may also be manipulated as nodes instead of as simple strings. It is fairly rare that you must do this, however, so this usage is not yet documented.
|:class:`DOMImplementation`||:ref:`dom-implementation-objects`||Interface to the underlying implementation.|
|:class:`Node`||:ref:`dom-node-objects`||Base interface for most objects in a document.|
|:class:`NodeList`||:ref:`dom-nodelist-objects`||Interface for a sequence of nodes.|
|:class:`DocumentType`||:ref:`dom-documenttype-objects`||Information about the declarations needed to process a document.|
|:class:`Document`||:ref:`dom-document-objects`||Object which represents an entire document.|
|:class:`Element`||:ref:`dom-element-objects`||Element nodes in the document hierarchy.|
|:class:`Attr`||:ref:`dom-attr-objects`||Attribute value nodes on element nodes.|
|:class:`Comment`||:ref:`dom-comment-objects`||Representation of comments in the source document.|
|:class:`Text`||:ref:`dom-text-objects`||Nodes containing textual content from the document.|
|:class:`ProcessingInstruction`||:ref:`dom-pi-objects`||Processing instruction representation.|
An additional section describes the exceptions defined for working with the DOM in Python.
The :class:`DOMImplementation` interface provides a way for applications to determine the availability of particular features in the DOM they are using. DOM Level 2 added the ability to create new :class:`Document` and :class:`DocumentType` objects using the :class:`DOMImplementation` as well.
All of the components of an XML document are subclasses of :class:`Node`.
A :class:`NodeList` represents a sequence of nodes. These objects are used in two ways in the DOM Core recommendation: the :class:`Element` objects provides one as its list of child nodes, and the :meth:`getElementsByTagName` and :meth:`getElementsByTagNameNS` methods of :class:`Node` return objects with this interface to represent query results.
The DOM Level 2 recommendation defines one method and one attribute for these objects:
In addition, the Python DOM interface requires that some additional support is provided to allow :class:`NodeList` objects to be used as Python sequences. All :class:`NodeList` implementations must include support for :meth:`__len__` and :meth:`__getitem__`; this allows iteration over the :class:`NodeList` in :keyword:`for` statements and proper support for the :func:`len` built-in function.
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 :class:`DocumentType` object. The :class:`DocumentType` for a document is available from the :class:`Document` object's :attr:`doctype` attribute; if there is no DOCTYPE declaration for the document, the document's :attr:`doctype` attribute will be set to None instead of an instance of this interface.
There are also experimental methods that give this class more mapping behavior. You can use them or you can use the standardized :meth:`getAttribute\*` family of methods on the :class:`Element` objects.
Text and CDATASection Objects
The :class:`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 :class:`CDATASection` objects. These two interfaces are identical, but provide different values for the :attr:`nodeType` attribute.
These interfaces extend the :class:`Node` interface. They cannot have child nodes.
The use of a :class:`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. A single CDATA section may be represented by more than one node in the document tree. There is no way to determine whether two adjacent :class:`CDATASection` nodes represent different CDATA marked sections.
Represents a processing instruction in the XML document; this inherits from the :class:`Node` interface and cannot have child nodes.
The DOM Level 2 recommendation defines a single exception, :exc:`DOMException`, and a number of constants that allow applications to determine what sort of error occurred. :exc:`DOMException` instances carry a :attr:`code` attribute that provides the appropriate value for the specific exception.
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. The implementations must raise the appropriate specific exception, each of which carries the appropriate value for the :attr:`code` attribute.
The exception codes defined in the DOM recommendation map to the exceptions described above according to this table:
This section describes the conformance requirements and relationships between the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for Python.
The IDL types used in the DOM specification are mapped to Python types according to the following table.
|IDL Type||Python Type|
|boolean||bool or int|
|DOMString||str or bytes|
The mapping from OMG IDL to Python defines accessor functions for IDL attribute declarations in much the way the Java mapping does. Mapping the IDL declarations
readonly attribute string someValue; attribute string anotherValue;
yields three accessor functions: a "get" method for :attr:`someValue` (:meth:`_get_someValue`), and "get" and "set" methods for :attr:`anotherValue` (:meth:`_get_anotherValue` and :meth:`_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 :exc:`AttributeError`.
The Python DOM API, however, does require that normal attribute access work. 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. 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. Attributes that are declared readonly may not restrict write access in all DOM implementations.
In the Python DOM API, accessor functions are not required. 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. "Set" accessors should never be provided for readonly attributes.
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 :meth:`getElementsByTagName`, being "live". The Python DOM API does not require implementations to enforce such requirements.