xml.dom — The Document Object Model API

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


The Document Object Model, or “DOM,” is a cross-language API from the World WideWeb Consortium (W3C) for accessing and modifying XML documents. A DOMimplementation presents an XML document as a tree structure, or allows clientcode to build such a structure from scratch. It then gives access to thestructure through a set of objects which provided well-known interfaces.

The DOM is extremely useful for random-access applications. SAX only allows youa view of one bit of the document at a time. If you are looking at one SAXelement, you have no access to another. If you are looking at a text node, youhave no access to a containing element. When you write a SAX application, youneed to keep track of your program’s position in the document somewhere in yourown code. SAX does not do it for you. Also, if you need to look ahead in theXML document, you are just out of luck.

Some applications are simply impossible in an event driven model with no accessto 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 treerepresentation for XML data.

The Document Object Model is being defined by the W3C in stages, or “levels” intheir terminology. The Python mapping of the API is substantially based on theDOM Level 2 recommendation.

DOM applications typically start by parsing some XML into a DOM. How this isaccomplished is not covered at all by DOM Level 1, and Level 2 provides onlylimited improvements: There is aDOMImplementation object class whichprovides access toDocument creation methods, but no way to access anXML reader/parser/Document builder in an implementation-independent way. Thereis also no well-defined way to access these methods without an existingDocument object. In Python, each DOM implementation will provide afunctiongetDOMImplementation(). DOM Level 3 adds a Load/Storespecification, which defines an interface to the reader, but this is not yetavailable in the Python standard library.

Once you have a DOM document object, you can access the parts of your XMLdocument through its properties and methods. These properties are defined inthe DOM specification; this portion of the reference manual describes theinterpretation 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 IDLversion of the specification, but strict compliance is not required (thoughimplementations are free to support the strict mapping from IDL). See sectionConformance for a detailed discussion of mapping requirements.

See also

Document Object Model (DOM) Level 2 Specification

The W3C recommendation upon which the Python DOM API is based.

Document Object Model (DOM) Level 1 Specification

The W3C recommendation for the DOM supported byxml.dom.minidom.

Python Language Mapping Specification

This specifies the mapping from OMG IDL to Python.

Module Contents

Thexml.dom contains the following functions:

xml.dom.registerDOMImplementation(name,factory)

Register thefactory function with the namename. The factory functionshould return an object which implements theDOMImplementationinterface. The factory function can return the same object every time, or a newone for each call, as appropriate for the specific implementation (e.g. if thatimplementation supports some customization).

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

Return a suitable DOM implementation. Thename is either well-known, themodule name of a DOM implementation, orNone. If it is notNone, importsthe corresponding module and returns aDOMImplementation object if theimport succeeds. If no name is given, and if the environment variablePYTHON_DOM is set, this variable is used to find the implementation.

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

Some convenience constants are also provided:

xml.dom.EMPTY_NAMESPACE

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

xml.dom.XML_NAMESPACE

The namespace URI associated with the reserved prefixxml, as defined byNamespaces in XML (section 4).

xml.dom.XMLNS_NAMESPACE

The namespace URI for namespace declarations, as defined byDocument ObjectModel (DOM) Level 2 Core Specification (section 1.1.8).

xml.dom.XHTML_NAMESPACE

The URI of the XHTML namespace as defined byXHTML 1.0: The ExtensibleHyperText Markup Language (section 3.1.1).

In addition,xml.dom contains a baseNode class and the DOMexception classes. TheNode class provided by this module does notimplement any of the methods or attributes defined by the DOM specification;concrete DOM implementations must provide those. TheNode classprovided as part of this module does provide the constants used for thenodeType attribute on concreteNode objects; they are locatedwithin the class rather than at the module level to conform with the DOMspecifications.

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 simplestrings. It is fairly rare that you must do this, however, so this usage is notyet documented.

Interface

Section

Purpose

DOMImplementation

DOMImplementation Objects

Interface to the underlyingimplementation.

Node

Node Objects

Base interface for most objectsin a document.

NodeList

NodeList Objects

Interface for a sequence ofnodes.

DocumentType

DocumentType Objects

Information about thedeclarations needed to processa document.

Document

Document Objects

Object which represents anentire document.

Element

Element Objects

Element nodes in the documenthierarchy.

Attr

Attr Objects

Attribute value nodes onelement nodes.

Comment

Comment Objects

Representation of comments inthe source document.

Text

Text and CDATASection Objects

Nodes containing textualcontent from the document.

ProcessingInstruction

ProcessingInstruction Objects

Processing instructionrepresentation.

An additional section describes the exceptions defined for working with the DOMin Python.

DOMImplementation Objects

TheDOMImplementation interface provides a way for applications todetermine the availability of particular features in the DOM they are using.DOM Level 2 added the ability to create newDocument andDocumentType objects using theDOMImplementation as well.

DOMImplementation.hasFeature(feature,version)

ReturnTrue if the feature identified by the pair of stringsfeature andversion is implemented.

DOMImplementation.createDocument(namespaceUri,qualifiedName,doctype)

Return a newDocument object (the root of the DOM), with a childElement object having the givennamespaceUri andqualifiedName. Thedoctype must be aDocumentType object created bycreateDocumentType(), orNone. In the Python DOM API, the first twoarguments can also beNone in order to indicate that noElementchild is to be created.

DOMImplementation.createDocumentType(qualifiedName,publicId,systemId)

Return a newDocumentType object that encapsulates the givenqualifiedName,publicId, andsystemId strings, representing theinformation contained in an XML document type declaration.

Node Objects

All of the components of an XML document are subclasses ofNode.

Node.nodeType

An integer representing the node type. Symbolic constants for the types are ontheNode 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.

Node.parentNode

The parent of the current node, orNone for the document node. The value isalways aNode object orNone. ForElement nodes, thiswill be the parent element, except for the root element, in which case it willbe theDocument object. ForAttr nodes, this is alwaysNone. This is a read-only attribute.

Node.attributes

ANamedNodeMap of attribute objects. Only elements have actual valuesfor this; others provideNone for this attribute. This is a read-onlyattribute.

Node.previousSibling

The node that immediately precedes this one with the same parent. Forinstance the element with an end-tag that comes just before theselfelement’s start-tag. Of course, XML documents are made up of more than justelements 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 beNone. This is a read-only attribute.

Node.nextSibling

The node that immediately follows this one with the same parent. See alsopreviousSibling. If this is the last child of the parent, thisattribute will beNone. 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, orNone. This is a read-onlyattribute.

Node.lastChild

The last child of the node, if there are any, orNone. This is a read-onlyattribute.

Node.localName

The part of thetagName following the colon if there is one, else theentiretagName. The value is a string.

Node.prefix

The part of thetagName preceding the colon if there is one, else theempty string. The value is a string, orNone.

Node.namespaceURI

The namespace associated with the element name. This will be a string orNone. This is a read-only attribute.

Node.nodeName

This has a different meaning for each node type; see the DOM specification fordetails. You can always get the information you would get here from anotherproperty such as thetagName property for elements or thenameproperty for attributes. For all node types, the value of this attribute will beeither a string orNone. This is a read-only attribute.

Node.nodeValue

This has a different meaning for each node type; see the DOM specification fordetails. The situation is similar to that withnodeName. The value isa string orNone.

Node.hasAttributes()

ReturnTrue if the node has any attributes.

Node.hasChildNodes()

ReturnTrue if the node has any child nodes.

Node.isSameNode(other)

ReturnTrue ifother refers to the same node as this node. This is especiallyuseful for DOM implementations which use any sort of proxy architecture (becausemore 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 “workingdraft” stage, but this particular interface appears uncontroversial. Changesfrom the W3C will not necessarily affect this method in the Python DOM interface(though any new W3C API for this would also be supported).

Node.appendChild(newChild)

Add a new child node to this node at the end of the list ofchildren, returningnewChild. If the node was already inthe tree, it is removed first.

Node.insertBefore(newChild,refChild)

Insert a new child node before an existing child. It must be the case thatrefChild is a child of this node; if not,ValueError is raised.newChild is returned. IfrefChild isNone, it insertsnewChild at theend of the children’s list.

Node.removeChild(oldChild)

Remove a child node.oldChild must be a child of this node; if not,ValueError is raised.oldChild is returned on success. IfoldChildwill not be used further, itsunlink() method should be called.

Node.replaceChild(newChild,oldChild)

Replace an existing node with a new node. It must be the case thatoldChildis a child of this node; if not,ValueError is raised.

Node.normalize()

Join adjacent text nodes so that all stretches of text are stored as singleText instances. This simplifies processing text from a DOM tree formany applications.

Node.cloneNode(deep)

Clone this node. Settingdeep means to clone all child nodes as well. Thisreturns the clone.

NodeList Objects

ANodeList represents a sequence of nodes. These objects are used intwo ways in the DOM Core recommendation: anElement object providesone as its list of child nodes, and thegetElementsByTagName() andgetElementsByTagNameNS() methods ofNode return objects with thisinterface to represent query results.

The DOM Level 2 recommendation defines one method and one attribute for theseobjects:

NodeList.item(i)

Return thei’th item from the sequence, if there is one, orNone. Theindexi is not allowed to be less than zero or greater than or equal to thelength of the sequence.

NodeList.length

The number of nodes in the sequence.

In addition, the Python DOM interface requires that some additional support isprovided to allowNodeList objects to be used as Python sequences. AllNodeList implementations must include support for__len__() and__getitem__(); this allows iteration over theNodeList infor statements and proper support for thelen() built-infunction.

If a DOM implementation supports modification of the document, theNodeList implementation must also support the__setitem__() and__delitem__() methods.

DocumentType Objects

Information about the notations and entities declared by a document (includingthe external subset if the parser uses it and can provide the information) isavailable from aDocumentType object. TheDocumentType for adocument is available from theDocument object’sdoctypeattribute; if there is noDOCTYPE declaration for the document, thedocument’sdoctype attribute will be set toNone instead of aninstance of this interface.

DocumentType is a specialization ofNode, and adds thefollowing attributes:

DocumentType.publicId

The public identifier for the external subset of the document type definition.This will be a string orNone.

DocumentType.systemId

The system identifier for the external subset of the document type definition.This will be a URI as a string, orNone.

DocumentType.internalSubset

A string giving the complete internal subset from the document. This does notinclude the brackets which enclose the subset. If the document has no internalsubset, this should beNone.

DocumentType.name

The name of the root element as given in theDOCTYPE declaration, ifpresent.

DocumentType.entities

This is aNamedNodeMap 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 beNone if the information is not provided by the parser, or if no entities aredefined.

DocumentType.notations

This is aNamedNodeMap giving the definitions of notations. Fornotation names defined more than once, only the first definition is provided(others are ignored as required by the XML recommendation). This may beNone if the information is not provided by the parser, or if no notationsare defined.

Document Objects

ADocument represents an entire XML document, including its constituentelements, attributes, processing instructions, comments etc. Remember that itinherits properties fromNode.

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 thedocument when it is created. You need to explicitly insert it with one of theother methods such asinsertBefore() orappendChild().

Document.createElementNS(namespaceURI,tagName)

Create and return a new element with a namespace. ThetagName may have aprefix. The element is not inserted into the document when it is created. Youneed to explicitly insert it with one of the other methods such asinsertBefore() orappendChild().

Document.createTextNode(data)

Create and return a text node containing the data passed as a parameter. Aswith the other creation methods, this one does not insert the node into thetree.

Document.createComment(data)

Create and return a comment node containing the data passed as a parameter. Aswith the other creation methods, this one does not insert the node into thetree.

Document.createProcessingInstruction(target,data)

Create and return a processing instruction node containing thetarget anddata passed as parameters. As with the other creation methods, this one doesnot insert the node into the tree.

Document.createAttribute(name)

Create and return an attribute node. This method does not associate theattribute node with any particular element. You must usesetAttributeNode() on the appropriateElement object to use thenewly created attribute instance.

Document.createAttributeNS(namespaceURI,qualifiedName)

Create and return an attribute node with a namespace. ThetagName may have aprefix. This method does not associate the attribute node with any particularelement. You must usesetAttributeNode() on the appropriateElement object to use the newly created attribute instance.

Document.getElementsByTagName(tagName)

Search for all descendants (direct children, children’s children, etc.) with aparticular element type name.

Document.getElementsByTagNameNS(namespaceURI,localName)

Search for all descendants (direct children, children’s children, etc.) with aparticular namespace URI and localname. The localname is the part of thenamespace after the prefix.

Element Objects

Element is a subclass ofNode, so inherits all the attributesof that class.

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 theDocument class.

Element.getElementsByTagNameNS(namespaceURI,localName)

Same as equivalent method in theDocument class.

Element.hasAttribute(name)

ReturnTrue if the element has an attribute named byname.

Element.hasAttributeNS(namespaceURI,localName)

ReturnTrue if the element has an attribute named bynamespaceURI andlocalName.

Element.getAttribute(name)

Return the value of the attribute named byname as a string. If no suchattribute exists, an empty string is returned, as if the attribute had no value.

Element.getAttributeNode(attrname)

Return theAttr node for the attribute named byattrname.

Element.getAttributeNS(namespaceURI,localName)

Return the value of the attribute named bynamespaceURI andlocalName as astring. If no such attribute exists, an empty string is returned, as if theattribute had no value.

Element.getAttributeNodeNS(namespaceURI,localName)

Return an attribute value as a node, given anamespaceURI andlocalName.

Element.removeAttribute(name)

Remove an attribute by name. If there is no matching attribute, aNotFoundErr is raised.

Element.removeAttributeNode(oldAttr)

Remove and returnoldAttr from the attribute list, if present. IfoldAttr isnot present,NotFoundErr is raised.

Element.removeAttributeNS(namespaceURI,localName)

Remove an attribute by name. Note that it uses a localName, not a qname. Noexception 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 ifnecessary if thename attribute matches. If a replacement occurs, theold attribute node will be returned. IfnewAttr is already in use,InuseAttributeErr will be raised.

Element.setAttributeNodeNS(newAttr)

Add a new attribute node to the element, replacing an existing attribute ifnecessary if thenamespaceURI andlocalName attributes match.If a replacement occurs, the old attribute node will be returned. IfnewAttris already in use,InuseAttributeErr will be raised.

Element.setAttributeNS(namespaceURI,qname,value)

Set an attribute value from a string, given anamespaceURI and aqname.Note that a qname is the whole attribute name. This is different than above.

Attr Objects

Attr inherits fromNode, so inherits all its attributes.

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

Attr.prefix

The part of the name preceding the colon if there is one, else theempty string.

Attr.value

The text value of the attribute. This is a synonym for thenodeValue attribute.

NamedNodeMap Objects

NamedNodeMap doesnot inherit fromNode.

NamedNodeMap.length

The length of the attribute list.

NamedNodeMap.item(index)

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

There are also experimental methods that give this class more mapping behavior.You can use them or you can use the standardizedgetAttribute*() familyof methods on theElement objects.

Comment Objects

Comment represents a comment in the XML document. It is a subclass ofNode, but cannot have child nodes.

Comment.data

The content of the comment as a string. The attribute contains all charactersbetween the leading<!-- and trailing-->, but does notinclude them.

Text and CDATASection Objects

TheText interface represents text in the XML document. If the parserand DOM implementation support the DOM’s XML extension, portions of the textenclosed in CDATA marked sections are stored inCDATASection objects.These two interfaces are identical, but provide different values for thenodeType attribute.

These interfaces extend theNode interface. They cannot have childnodes.

Text.data

The content of the text node as a string.

Note

The use of aCDATASection node does not indicate that the noderepresents a complete CDATA marked section, only that the content of the nodewas part of a CDATA section. A single CDATA section may be represented by morethan one node in the document tree. There is no way to determine whether twoadjacentCDATASection nodes represent different CDATA marked sections.

ProcessingInstruction Objects

Represents a processing instruction in the XML document; this inherits from theNode interface and cannot have child nodes.

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

Exceptions

The DOM Level 2 recommendation defines a single exception,DOMException,and a number of constants that allow applications to determine what sort oferror occurred.DOMException instances carry acode attributethat provides the appropriate value for the specific exception.

The Python DOM interface provides the constants, but also expands the set ofexceptions so that a specific exception exists for each of the exception codesdefined by the DOM. The implementations must raise the appropriate specificexception, each of which carries the appropriate value for thecodeattribute.

exceptionxml.dom.DOMException

Base exception class used for all specific DOM exceptions. This exception classcannot be directly instantiated.

exceptionxml.dom.DomstringSizeErr

Raised when a specified range of text does not fit into a string. This is notknown to be used in the Python DOM implementations, but may be received from DOMimplementations not written in Python.

exceptionxml.dom.HierarchyRequestErr

Raised when an attempt is made to insert a node where the node type is notallowed.

exceptionxml.dom.IndexSizeErr

Raised when an index or size parameter to a method is negative or exceeds theallowed values.

exceptionxml.dom.InuseAttributeErr

Raised when an attempt is made to insert anAttr node that is alreadypresent elsewhere in the document.

exceptionxml.dom.InvalidAccessErr

Raised if a parameter or an operation is not supported on the underlying object.

exceptionxml.dom.InvalidCharacterErr

This exception is raised when a string parameter contains a character that isnot permitted in the context it’s being used in by the XML 1.0 recommendation.For example, attempting to create anElement node with a space in theelement type name will cause this error to be raised.

exceptionxml.dom.InvalidModificationErr

Raised when an attempt is made to modify the type of a node.

exceptionxml.dom.InvalidStateErr

Raised when an attempt is made to use an object that is not defined or is nolonger usable.

exceptionxml.dom.NamespaceErr

If an attempt is made to change any object in a way that is not permitted withregard to theNamespaces in XMLrecommendation, this exception is raised.

exceptionxml.dom.NotFoundErr

Exception when a node does not exist in the referenced context. For example,NamedNodeMap.removeNamedItem() will raise this if the node passed in doesnot exist in the map.

exceptionxml.dom.NotSupportedErr

Raised when the implementation does not support the requested type of object oroperation.

exceptionxml.dom.NoDataAllowedErr

This is raised if data is specified for a node which does not support data.

exceptionxml.dom.NoModificationAllowedErr

Raised on attempts to modify an object where modifications are not allowed (suchas for read-only nodes).

exceptionxml.dom.SyntaxErr

Raised when an invalid or illegal string is specified.

exceptionxml.dom.WrongDocumentErr

Raised when a node is inserted in a different document than it currently belongsto, and the implementation does not support migrating the node from one documentto the other.

The exception codes defined in the DOM recommendation map to the exceptionsdescribed above according to this table:

Constant

Exception

DOMSTRING_SIZE_ERR

DomstringSizeErr

HIERARCHY_REQUEST_ERR

HierarchyRequestErr

INDEX_SIZE_ERR

IndexSizeErr

INUSE_ATTRIBUTE_ERR

InuseAttributeErr

INVALID_ACCESS_ERR

InvalidAccessErr

INVALID_CHARACTER_ERR

InvalidCharacterErr

INVALID_MODIFICATION_ERR

InvalidModificationErr

INVALID_STATE_ERR

InvalidStateErr

NAMESPACE_ERR

NamespaceErr

NOT_FOUND_ERR

NotFoundErr

NOT_SUPPORTED_ERR

NotSupportedErr

NO_DATA_ALLOWED_ERR

NoDataAllowedErr

NO_MODIFICATION_ALLOWED_ERR

NoModificationAllowedErr

SYNTAX_ERR

SyntaxErr

WRONG_DOCUMENT_ERR

WrongDocumentErr

Conformance

This section describes the conformance requirements and relationships betweenthe Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping forPython.

Type Mapping

The IDL types used in the DOM specification are mapped to Python typesaccording to the following table.

IDL Type

Python Type

boolean

bool orint

int

int

longint

int

unsignedint

int

DOMString

str orbytes

null

None

Accessor Methods

The mapping from OMG IDL to Python defines accessor functions for IDLattribute declarations in much the way the Java mapping does.Mapping the IDL declarations

readonlyattributestringsomeValue;attributestringanotherValue;

yields three accessor functions: a “get” method forsomeValue(_get_someValue()), and “get” and “set” methods foranotherValue(_get_anotherValue() and_set_anotherValue()). The mapping, inparticular, does not require that the IDL attributes are accessible as normalPython attributes:object.someValue isnot required to work, and mayraise anAttributeError.

The Python DOM API, however,does require that normal attribute access work.This means that the typical surrogates generated by Python IDL compilers are notlikely to work, and wrapper objects may be needed on the client if the DOMobjects are accessed via CORBA. While this does require some additionalconsideration for CORBA DOM clients, the implementers with experience using DOMover CORBA from Python do not consider this a problem. Attributes that aredeclaredreadonly may not restrict write access in all DOMimplementations.

In the Python DOM API, accessor functions are not required. If provided, theyshould take the form defined by the Python IDL mapping, but these methods areconsidered unnecessary since the attributes are accessible directly from Python.“Set” accessors should never be provided forreadonly 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 ofgetElementsByTagName(), being “live”. The Python DOM API does not requireimplementations to enforce such requirements.