XML technologies / XML / Python & XML / The Python-DOM API
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
DOM is a collection of interfaces. Python implements every core interface, including:
These interfaces and their Python implementation are detailed here as a reference. We also briefly discuss 4DOM extensions.
DOMException
DOM operations may raise exceptions. W3C DOM defines an abstract exception with constants; specific errors are identified by catching the generic exception and inspecting attribute code. Python makes this more like other Python exceptions, providing a base class DOMException and a subclass for each specific error. Attribute code still contains a constant. Code handling one error should catch only its subclass in an except clause; generic DOM error handling should catch base class DOMException. All classes and constants are defined in module xml.dom.
Below, the first name is the exception class; the parenthesized name is the constant for attribute code.
IndexSizeErr (INDEX_SIZE_ERR)
Raised for negative or excessively large indices.
DOMStringSizeErr (DOMSTRING_SIZE_ERR)
Raised if the text range does not fit in a
DOMString.
HierarchyRequestErr (HIERARCHY_REQUEST_ERR)
A node is inserted where it does not belong.
WrongDocumentErr (WRONG_DOCUMENT_ERR)
A node is used in a document other than its creating document, which does not support it.
InvalidCharacterErr (INVALID_CHARACTER_ERR)
An invalid or forbidden character occurs, for example in a name. XML specifies invalid characters.
NoDataAllowedErr (NO_DATA_ALLOWED_ERR)
Data is specified in a node that cannot hold data.
NoModificationAllowedErr (NO_MODIFICATION_ALLOWED_ERR)
An object is modified where modification is forbidden.
NotFoundErr (NOT_FOUND_ERR)
A node is referenced in a context where it does not exist.
NotSupportedErr (NOT_SUPPORTED_ERR)
The requested object or operation type is unsupported.
InuseAttributeErr (INUSE_ATTRIBUTE_ERR)
An attribute already in use elsewhere is added.
InvalidStateErr (INVALID_STATE_ERR)
An unusable object is used.
SyntaxErr (SYNTAX_ERR)
An invalid or forbidden string is supplied.
InvalidModificationErr (INVALID_MODIFICATION_ERR)
The underlying object’s type is modified.
NamespaceErr (NAMESPACE_ERR)
An object is created or modified incorrectly with respect to namespaces.
InvalidAccessErr(INVALID_ACCESS_ERR)
A parameter or operation is unsupported by the object.
DOMImplementation
The interface DOMImplementation provides operations independent of any DOM instance.
hasFeature(feature, version)
Tests feature support and returns a Boolean.
createDocumentType(qualifiedName, publicId, systemId)
Creates and returns an empty
DocumentTypenode. Entity declarations and notations are unavailable. Future DOM versions are expected to support populating aDocumentType.
createDocument(namespaceURI, qualifiedName, doctype)
Creates an XML document of the specified type and root. Returns a
Documentobject.namespaceURIanddoctypemay beNoneif irrelevant to the new document.
DocumentFragment
Inherits from Node
DocumentFragment is a minimal document object for isolating parts of documents or holding temporary fragments during complex cut-and-paste operations. Fragments may contain any node types and have special insertion behavior. Most usefully, appending or inserting a DocumentFragment inserts the fragment’s children instead of the fragment itself.
A DocumentFragment is an interface inheriting from Node without adding methods or attributes.
Document
Inherits from Node
The interface Document represents a whole XML document, including root elements and document type. Children within Document have their own attribute ownerDocument linked to this parent.
doctype
Holds the document’s associated document type declaration, read-only and unmodifiable in DOM Level 2.
documentElement
The root element. Since DOM work naturally focuses on elements, quick access to the root is desirable.
implementation
The
DOMImplementationobject handling this document.
createAttribute(name)
Creates an object
Attrwith the specifiedname. Namespaces are supported bycreateAttributeNS.
createAttributeNS(namespaceURI, qualifiedName)
Like
createAttribute(name)but creates the attribute with parameternamespaceURI.
createCDATASection(data)
Creates and returns a
CDATAsection node with the supplied data.
createComment(data)
Creates and returns a comment node.
createDocumentFragment( )
Creates and returns an empty
DocumentFragmentobject.
createElement(tagname)
Creates an element with tag name
tagnameand returns an objectElement.
createElementNS(namespaceURI, qualifiedName)
Like
createElementbut associatesnamespaceURIwith the element.
createEntityReference(name)
Creates and returns an object
EntityReference; illegal characters may raise an exception.
createProcessingInstruction(target, data)
Creates and returns a node
ProcessingInstructionwith parameterstargetanddata.
createTextNode(data)
Creates and returns a text node containing
data.
getElementById(elementId)
Returns an object
Elementwith the ID, orNoneif absent. ID attributes must be declared in the DTD. A tag such as<account id="234"/>is not sufficient unless the DTD assigns ID type to its attribute. The objectDOMImplementationmust also know which attributes are IDs. IDs must be unique within each document.
getElementsByTagName(tagName)
Returns a
NodeListcontaining all elements namedtagNamein original parsing order.
getElementsByTagNameNS(namespaceURI, localName)
Returns a
NodeListof elements matching bothlocalNameandnamespaceURI.
importNode(importedNode, deep)
Imports a node from another document. The
Nodehas no parent. Attributes and the namespace of the importedNodeare identical. Different node types have specific rules and side effects.
Imported attribute nodes (
Attr) have no owner element and import all children.For
DocumentFragmentnodes, children are imported if parameterdeepis true.Documentnodes are not imported because aDocumentcannot contain anotherDocument.Elementnodes are imported with attributes, and children ifdeepis true.For
EntityReferencenodes, only the nodes themselves are copied regardless ofdeep. Defined entity values are imported too.Notationnodes can be imported, but DOM currently forbids modifyingDocumentType.ProcessingInstructionnodes are fully imported as expected.Charac-terData, includingCDATASectionandCommentnodes, are copied with theirdataattributes as expected.
Node
As the ancestor of much of DOM, class Node holds extensive information.
Node constants
Node defines constants identifying a node’s nodeType.
ELEMENT_NODE
The
Elementnode
ATTRIBUTE_NODE
The
Attrnode
TEXT_NODE
The
Textnode
CDATA_SECTION_NODE
The
CDATASectionnode
ENTITY_REFERENCE_NODE
The
EntityReferencenode
ENTITY_NODE
The
Entitynode
PROCESSING_INSTRUCTION_NODE
The
ProcessingInstructionnode
COMMENT_NODE
The
Commentnode
DOCUMENT_NODE
The
Documentnode
DOCUMENT_TYPE_NODE
The
DocumentTypenode
DOCUMENT_FRAGMENT_NODE
The
DocumentFragmentnode
NOTATION_NODE
The
Notationnode
Node attributes and methods
attributes
Contains a
NamedNodeMapwith this node’s attributes, orNone.
childNodes
Contains a
NodeListof every child, empty if none.
firstChild
The first child, convenient when structure is known. If childless,
None.
lastChild
Like
firstChildbut holds the last child; if childless,None.
localName
The qualified node name’s local part.
namespaceURI
The node’s namespace URI, or
Noneif absent.
nextSibling
The immediately following node, or
Noneif absent.
nodeName
The name depends on type.
TextandCharacterDatanodes have no name, just a type-identifying string. ForElementnodes, it is the tag name. Other named types return their corresponding name.
nodeType
An integer node type corresponding directly to constants in class
Node.
nodeValue
The value depends on type. Attributes hold their assigned value. For
ProcessingInstruction,CDATASection,CommentandTextnodes, it is their content. ForElementnodes, however, it is not descendant character data, butNone.
ownerDocument
The object
Documentowning this node.
parentNode
The immediate parent, possibly
Nonefor new, unattached nodes. Attribute nodes always haveNone.
prefix
The namespace prefix or
Noneif absent.
previousSibling
Like
nextSiblingbut associated with the previous node orNone.
appendChild(newChild)
Appends node
newChildto this node’sNodeList. An existing node is removed before being appended.
cloneNode(deep)
Returns an unattached, parentless duplicate. If parameter
deepis true, copies the entire subtree too.
hasChildNodes( )
Returns
trueorfalseaccording to whether children exist.
insertBefore(newChild, refChild)
Inserts the new node immediately before
refChildin the node’sNodeList. IfnewChildalready exists, it is removed first.
supports(feature, level)
Returns
trueorfalsedepending on DOM feature support for this node.
normalize( )
Traverses the full subtree, ensuring only markup structures such as elements, comments and processing instructions separate
Textnodes. This removes empty nodes or whitespace between text chunks.
removeChild(childNode)
Returns
childNodeand removes it from the node’sNodeList.
replaceChild(newChild, oldChild)
Replaces
oldChildwithnewChildand returnsoldChild. IfnewChildalready has another parent, it is removed.
NodeList
The interface NodeList is a generic list of children regardless of subtype. For example, Text nodes appear alongside Element and ProcessingInstruction nodes. This interface is not defined through interface Node.
length
Read-only node count. Length 10 means indices
0through9.
item(index)
Returns the node at the index in
NodeList, orNonefor an out-of-range index.
NamedNodeMap
Similar to NodeList but supports access by name. Node order is not guaranteed. It is not defined through interface Node.
length
Map size. As with
NodeList, length 10 means indices0through9.
getNamedItem(name)
Finds the node named by
name, returning it if found, otherwiseNone.
getNamedItemNS(namespaceURI, localName)
Returns the node matching parameters
localNameandnamespaceURI.
item(index)
Returns the node at position
index, orNoneifindexis out of range.
removeNamedItem(name)
Removes the node named by
name. If it is an XML attribute, anAttrnode, with a DTD default, that default is restored with the same URI, local name and prefix. Returns the removed node.
removeNamedItemNS(namespaceURI, localName)
Like
removeNamedItembut searches using bothnamespaceURIandlocalName. Returns the removed node.
setNamedItem(arg)
The first parameter
argshould be an object. An existing same-named node is replaced and returned. ReturnsNoneif adding without replacement.
setNamedItemNS(arg)
Like
setNamedItembut with namespace URI and local name, both from parameterargof typeNode.
CharacterData
Inherits from Node
The interface CharacterData is a subtype of Node with text methods. It represents no concrete node type, but underpins interfaces Text and Comment.
data
The node’s character data as a string.
length
Character count available through attribute
dataand methodsubstringData. Empty objects may have value0.
appendData(arg)
Appends string
argto character data.
deleteData(offset, count)
Deletes characters starting at
offsetup tooffset + count. A range beyond string length deletes fromoffsetto the end.
insertData(offest, arg)
Inserts character data starting at position
offset.
replaceData(offset, count, arg)
Replaces data starting at
offsetwith data inargup to positionoffset + count. Extra replacement text is appended if the original length is exceeded.
substringData(offset, count)
Extracts part of the node
CharacterData. Ifoffset + countexceeds the length, returns everything to the end.
Attr
Inherits from Node
The interface Attr is the Node interface for attributes. DOM does not regard Attr as part of the tree, so attributes parentNode, previousSibling and nextSibling for objects of type Attr are all None. Treat attributes as element properties. Attr nodes cannot be direct children of a DocumentFragment but may occur within an element inside a document fragment.
Values come from markup or DTD defaults. Children of an object Attr may be Text nodes or type EntityReference.
name
The attribute name.
ownerElement
The owning node
Element.
specified
Boolean: explicitly supplied values are
true, otherwise a DTD default was used. Alsotruefor edited or explicitly assigned values still equal to the default. If attributeownerElementisNonebecause the node has no associated element,specifiedis alsotrue.
value
The value in the key/value pair constituting the
Attrin anElement.
Element
Inherits from Node
An element of markup. Besides inherited methods from Node, provides attribute accessors.
tagName
The element type name. For
<stag drums="dale">, returns stringstag.
getAttribute(name)
Returns an attribute’s value without fetching the
Attrobject and using its accessors. Direct use of theAttrnode may sometimes be better, but element convenience methods usually suffice.
getAttributeNS(namespaceURI, localName)
Like
getAttributebut searches by namespace and name.
getAttributeNode(name)
Returns the actual object
Attrrather than the string value fromgetAttribute. ReturnsNoneif absent.
getAttributeNodeNS(namespaceURI, localName)
Returns a node
Attrmatching name and URI, orNoneif absent.
getElementsByTagName(tagName)
Returns a
NodeListof descendant nodesElementsharing the type name. Special value*matches every tag.
getElementsByTagNameNS(namespaceURI, localName)
Returns a
NodeListof descendants matching name and URI. Value*matches any URI or local name in the respective argument. Using*for both matches all descendants.
hasAttribute(name)
Returns
trueif attributenameis present or has a DTD default.
hasAttributeNS(namespaceURI, localName)
Returns
trueif an attribute with name and namespace exists or has a DTD default.
removeAttribute(name)
Removes the attribute named by
name. A DTD default takes effect immediately after removal.
removeAttributeNS(namespaceURI, localName)
Removes the attribute matching local name and namespace. A DTD default takes effect immediately.
removeAttributeNode(node)
Removes attribute node
node. Requires a complete objectAttrrather than a string name as in methodsremoveAttribute. Returns the removed node.
setAttribute(name, value)
Adds an attribute to
Elementusing the suppliedname/valuepair. Existing same-named entries are replaced. Text is literal; it creates noEntityReferenceor other complexAttrstructures; seesetAttributeNode.
setAttributeNS(namesapceURI, qualifiedName, value)
Like
setAttributebut associates a namespace URI and prefix.
setAttributeNode(node)
Adds an attribute to
Element. If parameternodeof typeAttrcontains a nodeTextor childrenEntityReference, they are added too. An existing attribute with the samenodeNameis replaced. ReturnsNoneunless replacing, in which case it returns the old attribute.
setAttributeNodeNS(node)
Like
setAttributeNode. An existing node with the same URI and local name is replaced and returned; otherwise it adds the attribute and returnsNone.
Text
Inherits from CharacterData
The interface Text represents text in an Element or Attribute. Text nodes cover text outside regular markup. Method normalize merges adjacent nodes Text for each text chunk. Interface CharacterData methods access and edit the data.
splitText(offset)
Splits the node in two at
offset. Data beforeoffsetremains; later data goes into a new adjacent nodeText, which is returned.
Comment
Inherits from CharacterData
The node Comment holds text in a Comment structure: <!-- Achtung, ein Kommentar -->. Use methods of CharacterData to edit comment content.
CDATASection
Inherits from Text
Supports editing nodes CDATASection. Unlike Text nodes, method normalize does not merge adjacent nodes CDATASection. CDATASection nodes may contain special characters otherwise confused with XML.
DocumentType
Inherits from Node
Represents the document DTD, or None if absent. DOM makes its attributes read-only because the W3C was uncertain how work on XML Schema would affect DTD use.
entities
Returns a new
NamedNodeMapof internal and external entities declared in the DTD. Parameter entities are excluded. Repeated entity declarations use the first only. Entries inNamedNodeMapimplement interfaceEntity. May beNoneif the parser provides no information or none are declared.
internalSubset
Internal DTD subset as a string, or
Noneif absent. Excludes enclosing brackets.
name
Root element name from the DTD.
notations
A
NamedNodeMapof DTD notations. Each entry implements interfaceNotation. Only the first duplicate declaration counts. May beNoneif information is unavailable or no notations exist.
publicId
External subset’s public identifier, or
Noneif absent.
systemId
External subset’s system identifier, or
Noneif absent.
Notation
Inherits from Node
Represents a Notation declared in the DTD. From Node, the inherited attribute nodeName provides the notation name.
publicId
Notation’s public identifier, or
Noneif absent.
systemId
Notation’s system identifier, or
Noneif absent.
Entity
Inherits from Node
Represents parsed and unparsed entities. A parser may expand them before building DOM, leaving no nodes EntityReference in the tree.
External entity values may be unavailable in non-validating parsers, which need not process them.
Entity nodes are read-only.
notationName
This value is
Nonefor parsed entities, otherwise the notation name.
puclicId
Entity public identifier, or
Noneif absent.
systemId
Entity system identifier, or
Noneif absent.
EntityReference
Inherits from Node
Empty interface for existing or newly inserted entity references. Character references and predefined entity references may be expanded during DOM creation. Then the parser creates no objects EntityReference.
ProcessingInstruction
Inherits from Node
A simple interface representing a processing instruction with two string attributes representing the data and target of the ProcessingInstruction.
data
The processing instruction’s content.
target
The processing instruction’s target.
4DOM extensions
PyXML’s 4DOM package provides proprietary extensions that may eventually enter W3C specifications. These classes read XML streams, pretty-print, provide convenient splitting and more. They are documented in PyXML/doc/4DOM/extensions.html in PyXML and are unavailable in other DOM implementations.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de