We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

The elementtree.ElementTree Module

The Element type is a flexible container object, designed to store hierarchical data structures in memory. The type can be described as a cross between a list and a dictionary.

Each element has a number of properties associated with it:

  • a tag. This is a string identifying what kind of data this element represents (the element type, in other words).
  • a number of attributes, stored in a Python dictionary.
  • a text string.
  • an optional tail string.
  • a number of child elements, stored in a Python sequence
To create an element instance, use the Element or SubElement factory functions.

The ElementTree class can be used to wrap an element structure, and convert it from and to XML.

Module Contents

_ElementInterface(tag, attrib) (class) [#]

Internal element class.

For more information about this class, see The _ElementInterface Class.

Comment(text=None) ⇒ Element [#]

Comment element factory. This factory function creates a special element that will be serialized as an XML comment.

The comment string can be either an 8-bit ASCII string or a Unicode string.

text
A string containing the comment string.
Returns:
An element instance, representing a comment.

dump(elem) [#]

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.

elem
An element tree or an individual element.

Element(tag, attrib={}, **extra) ⇒ Element [#]

Element factory. This function returns an object implementing the standard Element interface. The exact class or type of that object is implementation dependent, but it will always be compatible with the _ElementInterface class in this module.

The element name, attribute names, and attribute values can be either 8-bit ASCII strings or Unicode strings.

tag
The element name.
attrib
An optional dictionary, containing element attributes.
**extra
Additional attributes, given as keyword arguments.
Returns:
An element instance.

ElementTree(element=None, file=None) (class) [#]

ElementTree wrapper class.

element
Optional root element.
file=
Optional file handle or name. If given, the tree is initialized with the contents of this XML file.

For more information about this class, see The ElementTree Class.

fromstring (variable) [#]

Parses an XML document from a string constant. Same as XML.

source
A string containing XML data.
Returns:
An Element instance.

iselement(element) ⇒ flag [#]

Checks if an object appears to be a valid element object.

An
element instance.
Returns:
A true value if this is an element object.

parse(source, parser=None) [#]

Parses an XML document into an element tree.

source
A filename or file object containing XML data.
parser
An optional parser instance. If not given, the standard XMLTreeBuilder parser is used.
Returns:
An ElementTree instance

ProcessingInstruction(target, text=None) ⇒ Element [#]

PI element factory. This factory function creates a special element that will be serialized as an XML processing instruction.

target
A string containing the PI target.
text
A string containing the PI contents, if any.
Returns:
An element instance, representing a PI.

QName(text_or_uri, tag=None) (class) [#]

QName wrapper.

text
A string containing the QName value, in the form {uri}local, or, if the tag argument is given, the URI part of a QName.
tag
Optional tag. If given, the first argument is interpreted as an URI, and this argument is interpreted as a local name.
Returns:
An opaque object, representing the QName.

For more information about this class, see The QName Class.

SubElement(parent, tag, attrib={}, **extra) ⇒ Element [#]

Subelement factory. This function creates an element instance, and appends it to an existing element.

The element name, attribute names, and attribute values can be either 8-bit ASCII strings or Unicode strings.

parent
The parent element.
tag
The subelement name.
attrib
An optional dictionary, containing element attributes.
**extra
Additional attributes, given as keyword arguments.
Returns:
An element instance.

tostring(element, encoding=None) ⇒ string [#]

Generates a string representation of an XML element, including all subelements.

element
An Element instance.
Returns:
An encoded string containing the XML data.

TreeBuilder(element_factory=None) (class) [#]

Generic element structure builder.

element_factory
Optional element factory. This factory is called to create new Element instances, as necessary.

For more information about this class, see The TreeBuilder Class.

XML(text) ⇒ Element [#]

Parses an XML document from a string constant. This function can be used to embed “XML literals” in Python code.

source
A string containing XML data.
Returns:
An Element instance.

XMLID(text) ⇒ (Element, dictionary) [#]

Parses an XML document from a string constant, and also returns a dictionary which maps from element id:s to elements.

source
A string containing XML data.
Returns:
A tuple containing an Element instance and a dictionary.

XMLTreeBuilder(html=0, target=None) (class) [#]

Element structure builder for XML source data, based on the expat parser.

target=
Target object. If omitted, the builder uses an instance of the standard TreeBuilder class.
html=
Predefine HTML entities. This flag is not supported by the current implementation.

For more information about this class, see The XMLTreeBuilder Class.

The _ElementInterface Class

_ElementInterface(tag, attrib) (class) [#]

Internal element class. This class defines the Element interface, and provides a reference implementation of this interface.

You should not create instances of this class directly. Use the appropriate factory functions instead, such as Element and SubElement.

__delitem__(index) [#]

Deletes the given subelement.

index
What subelement to delete.
Raises IndexError:
If the given element does not exist.

__delslice__(start, stop) [#]

Deletes a number of subelements.

start
The first subelement to delete.
stop
The first subelement to leave in there.

__getitem__(index) [#]

Returns the given subelement.

index
What subelement to return.
Returns:
The given subelement.
Raises IndexError:
If the given element does not exist.

__getslice__(start, stop) [#]

Returns a list containing subelements in the given range.

start
The first subelement to return.
stop
The first subelement that shouldn’t be returned.
Returns:
A sequence object containing subelements.

__len__() [#]

Returns the number of subelements.

Returns:
The number of subelements.

__setitem__(index, element) [#]

Replaces the given subelement.

index
What subelement to replace.
element
The new element value.
Raises IndexError:
If the given element does not exist.
Raises AssertionError:
If element is not a valid object.

__setslice__(start, stop, elements) [#]

Replaces a number of subelements with elements from a sequence.

start
The first subelement to replace.
stop
The first subelement that shouldn’t be replaced.
elements
A sequence object with zero or more elements.
Raises AssertionError:
If a sequence member is not a valid object.

append(element) [#]

Adds a subelement to the end of this element.

element
The element to add.
Raises AssertionError:
If a sequence member is not a valid object.

attrib [#]

(Attribute) Element attribute dictionary. Where possible, use get, set, keys, and items to access element attributes.

clear() [#]

Resets an element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to None.

find(path) ⇒ Element or None [#]

Finds the first matching subelement, by tag name or path.

path
What element to look for.
Returns:
The first matching element, or None if no element was found.

findall(path) ⇒ list of Element instances [#]

Finds all matching subelements, by tag name or path.

path
What element to look for.
Returns:
A list or iterator containing all matching elements, in document order.

findtext(path, default=None) ⇒ string [#]

Finds text for the first matching subelement, by tag name or path.

path
What element to look for.
default
What to return if the element was not found.
Returns:
The text content of the first matching element, or the default value no element was found. Note that if the element has is found, but has no text content, this method returns an empty string.

get(key, default=None) ⇒ string or None [#]

Gets an element attribute.

key
What attribute to look for.
default
What to return if the attribute was not found.
Returns:
The attribute value, or the default value, if the attribute was not found.

getchildren() ⇒ list of Element instances [#]

Returns all subelements. The elements are returned in document order.

Returns:
A list of subelements.

getiterator(tag=None) ⇒ list or iterator [#]

Creates a tree iterator. The iterator loops over this element and all subelements, in document order, and returns all elements with a matching tag.

If the tree structure is modified during iteration, the result is undefined.

tag
What tags to look for (default is to return all elements).
Returns:
A list or iterator containing all the matching elements.

insert(index, element) [#]

Inserts a subelement at the given position in this element.

index
Where to insert the new subelement.
Raises AssertionError:
If the element is not a valid object.

items() ⇒ list of (string, string) tuples [#]

Gets element attributes, as a sequence. The attributes are returned in an arbitrary order.

Returns:
A list of (name, value) tuples for all attributes.

keys() ⇒ list of strings [#]

Gets a list of attribute names. The names are returned in an arbitrary order (just like for an ordinary Python dictionary).

Returns:
A list of element attribute names.

makeelement(tag, attrib) [#]

Creates a new element object of the same type as this element.

tag
Element tag.
attrib
Element attributes, given as a dictionary.
Returns:
A new element instance.

remove(element) [#]

Removes a matching subelement. Unlike the find methods, this method compares elements based on identity, not on tag value or contents.

element
What element to remove.
Raises ValueError:
If a matching element could not be found.
Raises AssertionError:
If the element is not a valid object.

set(key, value) [#]

Sets an element attribute.

key
What attribute to set.
value
The attribute value.

tail [#]

(Attribute) Text after this element’s end tag, but before the next sibling element’s start tag. This is either a string or the value None, if there was no text.

text [#]

(Attribute) Text before first subelement. This is either a string or the value None, if there was no text.

The ElementTree Class

ElementTree(element=None, file=None) (class) [#]

ElementTree wrapper class. This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML.

element
Optional root element.
file=
Optional file handle or name. If given, the tree is initialized with the contents of this XML file.

_setroot(element) [#]

Replaces the root element for this tree. This discards the current contents of the tree, and replaces it with the given element. Use with care.

element
An element instance.

find(path) ⇒ Element or None [#]

Finds the first toplevel element with given tag. Same as getroot().find(path).

path
What element to look for.
Returns:
The first matching element, or None if no element was found.

findall(path) ⇒ list of Element instances [#]

Finds all toplevel elements with the given tag. Same as getroot().findall(path).

path
What element to look for.
Returns:
A list or iterator containing all matching elements, in document order.

findtext(path, default=None) ⇒ string [#]

Finds the element text for the first toplevel element with given tag. Same as getroot().findtext(path).

path
What toplevel element to look for.
default
What to return if the element was not found.
Returns:
The text content of the first matching element, or the default value no element was found. Note that if the element has is found, but has no text content, this method returns an empty string.

getiterator(tag=None) ⇒ iterator [#]

Creates a tree iterator for the root element. The iterator loops over all elements in this tree, in document order.

tag
What tags to look for (default is to return all elements)
Returns:
An iterator.

getroot() ⇒ Element [#]

Gets the root element for this tree.

Returns:
An element instance.

parse(source, parser=None) ⇒ Element [#]

Loads an external XML document into this element tree.

source
A file name or file object.
parser
An optional parser instance. If not given, the standard XMLTreeBuilder parser is used.
Returns:
The document root element.

write(file, encoding=”us-ascii”) [#]

Writes the element tree to a file, as XML.

file
A file name, or a file object opened for writing.
encoding
Optional output encoding (default is US-ASCII).

The QName Class

QName(text_or_uri, tag=None) (class) [#]

QName wrapper. This can be used to wrap a QName attribute value, in order to get proper namespace handling on output.

text
A string containing the QName value, in the form {uri}local, or, if the tag argument is given, the URI part of a QName.
tag
Optional tag. If given, the first argument is interpreted as an URI, and this argument is interpreted as a local name.
Returns:
An opaque object, representing the QName.

The TreeBuilder Class

TreeBuilder(element_factory=None) (class) [#]

Generic element structure builder. This builder converts a sequence of start, data, and end method calls to a well-formed element structure.

You can use this class to build an element structure using a custom XML parser, or a parser for some other XML-like format.

element_factory
Optional element factory. This factory is called to create new Element instances, as necessary.

close() ⇒ Element [#]

Flushes the parser buffers, and returns the toplevel documen element.

Returns:
An Element instance.

data(data) [#]

Adds text to the current element.

data
A string. This should be either an 8-bit string containing ASCII text, or a Unicode string.

end(tag) ⇒ Element [#]

Closes the current element.

tag
The element name.
Returns:
The closed element.

start(tag, attrs) ⇒ Element [#]

Opens a new element.

tag
The element name.
attrib
A dictionary containing element attributes.
Returns:
The opened element.

The XMLTreeBuilder Class

XMLTreeBuilder(html=0, target=None) (class) [#]

Element structure builder for XML source data, based on the expat parser.

target=
Target object. If omitted, the builder uses an instance of the standard TreeBuilder class.
html=
Predefine HTML entities. This flag is not supported by the current implementation.

close() ⇒ Element [#]

Finishes feeding data to the parser.

Returns:
An element structure.

doctype(name, pubid, system) [#]

Handles a doctype declaration.

name
Doctype name.
pubid
Public identifier.
system
System identifier.

feed(data) [#]

Feeds data to the parser.

data
Encoded data.