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:

To create an element instance, use the Element constructor or the SubElement factory function.

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

Module Contents

Comment(text=None) ⇒ Element [#]

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

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) (class) [#]

Element class.

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

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

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

ElementTree wrapper class.

element
Optional root element.
file=
Optional file handle or file 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.

fromstringlist(sequence, parser=None) ⇒ Element [#]

Parses an XML document from a sequence of string fragments.

sequence
A list or other sequence containing XML data fragments.
parser
An optional parser instance. If not given, the standard XMLParser parser is used.
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.

iterparse(source, events=None, parser=None) [#]

Parses an XML document into an element tree incrementally, and reports what's going on to the user.

source
A filename or file object containing XML data.
events
A list of events to report back. If omitted, only "end" events are reported.
parser
An optional parser instance. If not given, the standard XMLParser parser is used.
Returns:
A (event, elem) iterator.

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 XMLParser 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 by the standard serializer.

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.

register_namespace(prefix, uri) [#]

Registers a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed.

prefix
Namespace prefix.
uri
Namespace uri. Tags and attributes in this namespace will be serialized with the given prefix, if at all possible.

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.

tostringlist(element, encoding=None) ⇒ sequence [#]

Generates a string representation of an XML element, including all subelements. The string is returned as a sequence of string fragments.

element
An Element instance.
Returns:
A sequence object 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, parser=None) ⇒ 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.
parser
An optional parser instance. If not given, the standard XMLParser parser is used.
Returns:
An Element instance.

XMLID(text, parser=None) ⇒ (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.
parser
An optional parser instance. If not given, the standard XMLParser parser is used.
Returns:
A tuple containing an Element instance and a dictionary.

XMLParser(html=0, target=None, encoding=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.
encoding=
Optional encoding. If given, the value overrides the encoding specified in the XML file.

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

The Element Class

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

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

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.

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

extend(elements) [#]

Appends subelements from a sequence.

elements
A sequence object with zero or more elements.
Raises AssertionError:
If a subelement is not a valid object.

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 [#]

(Deprecated) Returns all subelements. The elements are returned in document order.

Returns:
A list of subelements.

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.

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

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.

tag [#]

(Attribute) Element tag.

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

getroot() ⇒ Element [#]

Gets the root element for this tree.

Returns:
An element instance.

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

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 XMLParser parser is used.
Returns:
The document root element.

write(file, encoding="us-ascii", xml_declaration=None) [#]

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).
xml_declaration=
Controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8. None is default.

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 builder buffers, and returns the toplevel document 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 XMLParser Class

XMLParser(html=0, target=None, encoding=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.
encoding=
Optional encoding. If given, the value overrides the encoding specified in the XML file.

close() ⇒ Element [#]

Finishes feeding data to the parser.

Returns:
An element structure.

feed(data) [#]

Feeds data to the parser.

data
Encoded data.