Navigation

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 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. There
is also no well-defined way to access these methods without an existing
Document object. In Python, each DOM implementation will provide a
function 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
Conformance for a detailed discussion of mapping requirements.

Register the factory function with the name name. The factory function
should return an object which implements the DOMImplementation
interface. 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).

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

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

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

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.

The 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 Document and
DocumentType objects using the DOMImplementation as well.

Return a new Document object (the root of the DOM), with a child
Element object having the given namespaceUri and qualifiedName. The
doctype must be a DocumentType object created by
createDocumentType(), or None. 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.

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.
This is a read-only attribute.

The parent of the current node, or None for the document node. The value is
always a Node object or None. For Element nodes, this
will be the parent element, except for the root element, in which case it will
be the Document object. For Attr nodes, this is always
None. This is a read-only attribute.

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. Of course, XML documents are made up of more than just
elements so the previous sibling could be text, a comment, or something else.
If this node is the first child of the parent, this attribute will be
None. This is a read-only attribute.

This has a different meaning for each node type; see the DOM specification for
details. 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. For all node types, the value of this attribute will be
either a string or None. This is a read-only attribute.

Returns true if other refers to the same node as this node. 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).

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. 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).

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.
newChild is returned. If refChild is None, it inserts newChild at the
end of the children’s list.

A NodeList represents a sequence of nodes. These objects are used in
two ways in the DOM Core recommendation: the Element objects 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.

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 NodeList objects to be used as Python sequences. 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.

If a DOM implementation supports modification of the document, the
NodeList implementation must also support the __setitem__() and
__delitem__() methods.

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 is a specialization of Node, and adds the
following attributes:

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

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

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().

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

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.

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

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

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

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

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.

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.

These interfaces extend the Node interface. They cannot have child
nodes.

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. 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 CDATASection nodes represent different CDATA marked sections.

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. DOMException instances carry a 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 code
attribute.

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.
For example, attempting to create an Element node with a space in the
element type name will cause this error to be raised.

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

readonlyattributestringsomeValue;attributestringanotherValue;

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.

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
getElementsByTagName(), being “live”. The Python DOM API does not require
implementations to enforce such requirements.