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 DocumentType node. Entity declarations and notations are unavailable. Future DOM versions are expected to support populating a DocumentType.

createDocument(namespaceURI, qualifiedName, doctype)

Creates an XML document of the specified type and root. Returns a Document object. namespaceURI and doctype may be None if 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 DOMImplementation object handling this document.

createAttribute(name)

Creates an object Attr with the specified name. Namespaces are supported by createAttributeNS.

createAttributeNS(namespaceURI, qualifiedName)

Like createAttribute(name) but creates the attribute with parameter namespaceURI.

createCDATASection(data)

Creates and returns a CDATA section node with the supplied data.

createComment(data)

Creates and returns a comment node.

createDocumentFragment( )

Creates and returns an empty DocumentFragment object.

createElement(tagname)

Creates an element with tag name tagname and returns an object Element.

createElementNS(namespaceURI, qualifiedName)

Like createElement but associates namespaceURI with the element.

createEntityReference(name)

Creates and returns an object EntityReference; illegal characters may raise an exception.

createProcessingInstruction(target, data)

Creates and returns a node ProcessingInstruction with parameters target and data.

createTextNode(data)

Creates and returns a text node containing data.

getElementById(elementId)

Returns an object Element with the ID, or None if 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 object DOMImplementation must also know which attributes are IDs. IDs must be unique within each document.

getElementsByTagName(tagName)

Returns a NodeList containing all elements named tagName in original parsing order.

getElementsByTagNameNS(namespaceURI, localName)

Returns a NodeList of elements matching both localName and namespaceURI.

importNode(importedNode, deep)

Imports a node from another document. The Node has no parent. Attributes and the namespace of the imported Node are identical. Different node types have specific rules and side effects.

  • Imported attribute nodes (Attr) have no owner element and import all children.

  • For DocumentFragment nodes, children are imported if parameter deep is true.

  • Document nodes are not imported because a Document cannot contain another Document.

  • Element nodes are imported with attributes, and children if deep is true.

  • For EntityReference nodes, only the nodes themselves are copied regardless of deep. Defined entity values are imported too.

  • Notation nodes can be imported, but DOM currently forbids modifying DocumentType.

  • ProcessingInstruction nodes are fully imported as expected. Charac-terData, including CDATASection and Comment nodes, are copied with their data attributes 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 Element node

ATTRIBUTE_NODE

The Attr node

TEXT_NODE

The Text node

CDATA_SECTION_NODE

The CDATASection node

ENTITY_REFERENCE_NODE

The EntityReference node

ENTITY_NODE

The Entity node

PROCESSING_INSTRUCTION_NODE

The ProcessingInstruction node

COMMENT_NODE

The Comment node

DOCUMENT_NODE

The Document node

DOCUMENT_TYPE_NODE

The DocumentType node

DOCUMENT_FRAGMENT_NODE

The DocumentFragment node

NOTATION_NODE

The Notation node

Node attributes and methods

attributes

Contains a NamedNodeMap with this node’s attributes, or None.

childNodes

Contains a NodeList of every child, empty if none.

firstChild

The first child, convenient when structure is known. If childless, None.

lastChild

Like firstChild but holds the last child; if childless, None.

localName

The qualified node name’s local part.

namespaceURI

The node’s namespace URI, or None if absent.

nextSibling

The immediately following node, or None if absent.

nodeName

The name depends on type. Text and CharacterData nodes have no name, just a type-identifying string. For Element nodes, 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, Comment and Text nodes, it is their content. For Element nodes, however, it is not descendant character data, but None.

ownerDocument

The object Document owning this node.

parentNode

The immediate parent, possibly None for new, unattached nodes. Attribute nodes always have None.

prefix

The namespace prefix or None if absent.

previousSibling

Like nextSibling but associated with the previous node or None.

appendChild(newChild)

Appends node newChild to this node’s NodeList. An existing node is removed before being appended.

cloneNode(deep)

Returns an unattached, parentless duplicate. If parameter deep is true, copies the entire subtree too.

hasChildNodes( )

Returns true or false according to whether children exist.

insertBefore(newChild, refChild)

Inserts the new node immediately before refChild in the node’s NodeList. If newChild already exists, it is removed first.

supports(feature, level)

Returns true or false depending on DOM feature support for this node.

normalize( )

Traverses the full subtree, ensuring only markup structures such as elements, comments and processing instructions separate Text nodes. This removes empty nodes or whitespace between text chunks.

removeChild(childNode)

Returns childNode and removes it from the node’s NodeList.

replaceChild(newChild, oldChild)

Replaces oldChild with newChild and returns oldChild. If newChild already 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 0 through 9.

item(index)

Returns the node at the index in NodeList, or None for 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 indices 0 through 9.

getNamedItem(name)

Finds the node named by name, returning it if found, otherwise None.

getNamedItemNS(namespaceURI, localName)

Returns the node matching parameters localName and namespaceURI.

item(index)

Returns the node at position index, or None if index is out of range.

removeNamedItem(name)

Removes the node named by name. If it is an XML attribute, an Attr node, with a DTD default, that default is restored with the same URI, local name and prefix. Returns the removed node.

removeNamedItemNS(namespaceURI, localName)

Like removeNamedItem but searches using both namespaceURI and localName. Returns the removed node.

setNamedItem(arg)

The first parameter arg should be an object. An existing same-named node is replaced and returned. Returns None if adding without replacement.

setNamedItemNS(arg)

Like setNamedItem but with namespace URI and local name, both from parameter arg of type Node.

 

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 data and method substringData. Empty objects may have value 0.

appendData(arg)

Appends string arg to character data.

deleteData(offset, count)

Deletes characters starting at offset up to offset + count. A range beyond string length deletes from offset to the end.

insertData(offest, arg)

Inserts character data starting at position offset.

replaceData(offset, count, arg)

Replaces data starting at offset with data in arg up to position offset + count. Extra replacement text is appended if the original length is exceeded.

substringData(offset, count)

Extracts part of the node CharacterData. If offset + count exceeds 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. Also true for edited or explicitly assigned values still equal to the default. If attribute ownerElement is None because the node has no associated element, specified is also true.

value

The value in the key/value pair constituting the Attr in an Element.

 

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 string stag.

getAttribute(name)

Returns an attribute’s value without fetching the Attr object and using its accessors. Direct use of the Attr node may sometimes be better, but element convenience methods usually suffice.

getAttributeNS(namespaceURI, localName)

Like getAttribute but searches by namespace and name.

getAttributeNode(name)

Returns the actual object Attr rather than the string value from getAttribute. Returns None if absent.

getAttributeNodeNS(namespaceURI, localName)

Returns a node Attr matching name and URI, or None if absent.

getElementsByTagName(tagName)

Returns a NodeList of descendant nodes Element sharing the type name. Special value * matches every tag.

getElementsByTagNameNS(namespaceURI, localName)

Returns a NodeList of 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 true if attribute name is present or has a DTD default.

hasAttributeNS(namespaceURI, localName)

Returns true if 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 object Attr rather than a string name as in methods removeAttribute. Returns the removed node.

setAttribute(name, value)

Adds an attribute to Element using the supplied name/value pair. Existing same-named entries are replaced. Text is literal; it creates no EntityReference or other complex Attr structures; see setAttributeNode.

setAttributeNS(namesapceURI, qualifiedName, value)

Like setAttribute but associates a namespace URI and prefix.

setAttributeNode(node)

Adds an attribute to Element. If parameter node of type Attr contains a node Text or children EntityReference, they are added too. An existing attribute with the same nodeName is replaced. Returns None unless 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 returns None.

 

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 before offset remains; later data goes into a new adjacent node Text, 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 NamedNodeMap of internal and external entities declared in the DTD. Parameter entities are excluded. Repeated entity declarations use the first only. Entries in NamedNodeMap implement interface Entity. May be None if the parser provides no information or none are declared.

internalSubset

Internal DTD subset as a string, or None if absent. Excludes enclosing brackets.

name

Root element name from the DTD.

notations

A NamedNodeMap of DTD notations. Each entry implements interface Notation. Only the first duplicate declaration counts. May be None if information is unavailable or no notations exist.

publicId

External subset’s public identifier, or None if absent.

systemId

External subset’s system identifier, or None if 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 None if absent.

systemId

Notation’s system identifier, or None if 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 None for parsed entities, otherwise the notation name.

puclicId

Entity public identifier, or None if absent.

systemId

Entity system identifier, or None if 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.

  

Back to top

 

 

 

back to top