XML is an inherently hierarchical data format, and the most natural way to
represent it is with a tree. ET has two classes for this purpose -
ElementTree represents the whole XML document as a tree, and
Element represents a single node in this tree. Interactions with
the whole document (reading and writing to/from files) are usually done
on the ElementTree level. Interactions with a single XML element
and its sub-elements are done on the Element level.

Not all elements of the XML input will end up as elements of the
parsed tree. Currently, this module skips over any XML comments,
processing instructions, and document type declarations in the
input. Nevertheless, trees built using this module’s API rather
than parsing from XML text can have comments and processing
instructions in them; they will be included when generating XML
output. A document type declaration may be accessed by passing a
custom TreeBuilder instance to the XMLParser
constructor.

Most parsing functions provided by this module require the whole document
to be read at once before returning any result. It is possible to use an
XMLParser and feed data into it incrementally, but it is a push API that
calls methods on a callback target, which is too low-level and inconvenient for
most needs. Sometimes what the user really wants is to be able to parse XML
incrementally, without blocking operations, while enjoying the convenience of
fully constructed Element objects.

The obvious use case is applications that operate in a non-blocking fashion
where the XML data is being received from a socket or read incrementally from
some storage device. In such cases, blocking reads are unacceptable.

Because it’s so flexible, XMLPullParser can be inconvenient to use for
simpler use-cases. If you don’t mind your application blocking on reading XML
data but would still like to have incremental parsing capabilities, take a look
at iterparse(). It can be useful when you’re reading a large XML document
and don’t want to hold it wholly in memory.

If the XML input has namespaces, tags and attributes
with prefixes in the form prefix:sometag get expanded to
{uri}sometag where the prefix is replaced by the full URI.
Also, if there is a default namespace,
that full URI gets prepended to all of the non-prefixed tags.

Here is an XML example that incorporates two namespaces, one with the
prefix “fictional” and the other serving as the default namespace:

This module provides limited support for
XPath expressions for locating elements in a
tree. The goal is to support a small subset of the abbreviated syntax; a full
XPath engine is outside the scope of the module.

Here’s an example that demonstrates some of the XPath capabilities of the
module. We’ll be using the countrydata XML document from the
Parsing XML section:

importxml.etree.ElementTreeasETroot=ET.fromstring(countrydata)# Top-level elementsroot.findall(".")# All 'neighbor' grand-children of 'country' children of the top-level# elementsroot.findall("./country/neighbor")# Nodes with name='Singapore' that have a 'year' childroot.findall(".//year/..[@name='Singapore']")# 'year' nodes that are children of nodes with name='Singapore'root.findall(".//*[@name='Singapore']/year")# All 'neighbor' nodes that are the second child of their parentroot.findall(".//neighbor[2]")

Selects all child elements with the given tag.
For example, spam selects all child elements
named spam, and spam/egg selects all
grandchildren named egg in all children named
spam.

*

Selects all child elements. For example, */egg
selects all grandchildren named egg.

.

Selects the current node. This is mostly useful
at the beginning of the path, to indicate that it’s
a relative path.

//

Selects all subelements, on all levels beneath the
current element. For example, .//egg selects
all egg elements in the entire tree.

..

Selects the parent element. Returns None if the
path attempts to reach the ancestors of the start
element (the element find was called on).

[@attrib]

Selects all elements that have the given attribute.

[@attrib='value']

Selects all elements for which the given attribute
has the given value. The value cannot contain
quotes.

[tag]

Selects all elements that have a child named
tag. Only immediate children are supported.

[.='text']

Selects all elements whose complete text content,
including descendants, equals the given text.

New in version 3.7.

[tag='text']

Selects all elements that have a child named
tag whose complete text content, including
descendants, equals the given text.

[position]

Selects all elements that are located at the given
position. The position can be either an integer
(1 is the first position), the expression last()
(for the last position), or a position relative to
the last position (e.g. last()-1).

Predicates (expressions within square brackets) must be preceded by a tag
name, an asterisk, or another predicate. position predicates must be
preceded by a tag name.

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 a bytestring or a Unicode string. text is a
string containing the comment string. Returns an element instance
representing a comment.

Note that XMLParser skips over comments in the input
instead of creating comment objects for them. An ElementTree will
only contain comment nodes if they have been inserted into to
the tree using one of the Element methods.

Parses an XML section from a string constant. Same as XML(). text
is a string containing XML data. parser is an optional parser instance.
If not given, the standard XMLParser parser is used.
Returns an Element instance.

Parses an XML document from a sequence of string fragments. sequence is a
list or other sequence containing XML data fragments. parser is an
optional parser instance. If not given, the standard XMLParser
parser is used. Returns an Element instance.

Parses an XML section into an element tree incrementally, and reports what’s
going on to the user. source is a filename or file object
containing XML data. events is a sequence of events to report back. The
supported events are the strings "start", "end", "start-ns" and
"end-ns" (the “ns” events are used to get detailed namespace
information). If events is omitted, only "end" events are reported.
parser is an optional parser instance. If not given, the standard
XMLParser parser is used. parser must be a subclass of
XMLParser and can only use the default TreeBuilder as a
target. Returns an iterator providing (event,elem) pairs.

Note that while iterparse() builds the tree incrementally, it issues
blocking reads on source (or the file it names). As such, it’s unsuitable
for applications where blocking reads can’t be made. For fully non-blocking
parsing, see XMLPullParser.

Note

iterparse() only guarantees that it has seen the “>” character of a
starting tag when it emits a “start” event, so the attributes are defined,
but the contents of the text and tail attributes are undefined at that
point. The same applies to the element children; they may or may not be
present.

Parses an XML section into an element tree. source is a filename or file
object containing XML data. parser is an optional parser instance. If
not given, the standard XMLParser parser is used. Returns an
ElementTree instance.

PI element factory. This factory function creates a special element that
will be serialized as an XML processing instruction. target is a string
containing the PI target. text is a string containing the PI contents, if
given. Returns an element instance, representing a processing instruction.

Note that XMLParser skips over processing instructions
in the input instead of creating comment objects for them. An
ElementTree will only contain processing instruction nodes if
they have been inserted into to the tree using one of the
Element methods.

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 is a namespace prefix. uri is a namespace uri. Tags and
attributes in this namespace will be serialized with the given prefix, if at
all possible.

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
bytestrings or Unicode strings. parent is the parent element. tag is
the subelement name. attrib is an optional dictionary, containing element
attributes. extra contains additional attributes, given as keyword
arguments. Returns an element instance.

Generates a string representation of an XML element, including all
subelements. element is an Element instance. encoding1 is
the output encoding (default is US-ASCII). Use encoding="unicode" to
generate a Unicode string (otherwise, a bytestring is generated). method
is either "xml", "html" or "text" (default is "xml").
short_empty_elements has the same meaning as in ElementTree.write().
Returns an (optionally) encoded string containing the XML data.

Generates a string representation of an XML element, including all
subelements. element is an Element instance. encoding1 is
the output encoding (default is US-ASCII). Use encoding="unicode" to
generate a Unicode string (otherwise, a bytestring is generated). method
is either "xml", "html" or "text" (default is "xml").
short_empty_elements has the same meaning as in ElementTree.write().
Returns a list of (optionally) encoded strings containing the XML data.
It does not guarantee any specific sequence, except that
b"".join(tostringlist(element))==tostring(element).

Parses an XML section from a string constant. This function can be used to
embed “XML literals” in Python code. text is a string containing XML
data. parser is an optional parser instance. If not given, the standard
XMLParser parser is used. Returns an Element instance.

Parses an XML section from a string constant, and also returns a dictionary
which maps from element id:s to elements. text is a string containing XML
data. parser is an optional parser instance. If not given, the standard
XMLParser parser is used. Returns a tuple containing an
Element instance and a dictionary.

This module provides limited support for
XInclude directives, via the xml.etree.ElementInclude helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree.

Here’s an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the {http://www.w3.org/2001/XInclude}include element and set the parse attribute to "xml", and use the href attribute to specify the document to include.

Default loader. This default loader reads an included resource from disk. href is a URL.
parse is for parse mode either “xml” or “text”. encoding
is an optional text encoding. If not given, encoding is utf-8. Returns the
expanded resource. If the parse mode is "xml", this is an ElementTree
instance. If the parse mode is “text”, this is a Unicode string. If the
loader fails, it can return None or raise an exception.

This function expands XInclude directives. elem is the root element. loader is
an optional resource loader. If omitted, it defaults to default_loader().
If given, it should be a callable that implements the same interface as
default_loader(). Returns the expanded resource. If the parse mode is
"xml", this is an ElementTree instance. If the parse mode is “text”,
this is a Unicode string. If the loader fails, it can return None or
raise an exception.

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
bytestrings or Unicode strings. tag is the element name. attrib is
an optional dictionary, containing element attributes. extra contains
additional attributes, given as keyword arguments.

These attributes can be used to hold additional data associated with
the element. Their values are usually strings but may be any
application-specific object. If the element is created from
an XML file, the text attribute holds either the text between
the element’s start tag and its first child or end tag, or None, and
the tail attribute holds either the text between the element’s
end tag and the next tag, or None. For the XML data

<a><b>1<c>2<d/>3</c></b>4</a>

the a element has None for both text and tail attributes,
the b element has text"1" and tail"4",
the c element has text"2" and tailNone,
and the d element has textNone and tail"3".

To collect the inner text of an element, see itertext(), for
example "".join(element.itertext()).

A dictionary containing the element’s attributes. Note that while the
attrib value is always a real mutable Python dictionary, an ElementTree
implementation may choose to use another internal representation, and
create the dictionary only if someone asks for it. To take advantage of
such implementations, use the dictionary methods below whenever possible.

Finds text for the first subelement matching match. match may be
a tag name or a path. Returns the text content
of the first matching element, or default if no element was found.
Note that if the matching element has no text content an empty string
is returned. namespaces is an optional mapping from namespace prefix
to full name.

Creates a tree iterator with the current element as the root.
The iterator iterates over this element and all elements below it, in
document (depth first) order. If tag is not None or '*', only
elements whose tag equals tag are returned from the iterator. If the
tree structure is modified during iteration, the result is undefined.

Loads an external XML section into this element tree. source is a file
name or file object. parser is an optional parser instance.
If not given, the standard XMLParser parser is used. Returns the
section root element.

Writes the element tree to a file, as XML. file is a file name, or a
file object opened for writing. encoding1 is the 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 or Unicode (default is None).
default_namespace sets the default XML namespace (for “xmlns”).
method is either "xml", "html" or "text" (default is
"xml").
The keyword-only short_empty_elements parameter controls the formatting
of elements that contain no content. If True (the default), they are
emitted as a single self-closed tag, otherwise they are emitted as a pair
of start/end tags.

The output is either a string (str) or binary (bytes).
This is controlled by the encoding argument. If encoding is
"unicode", the output is a string; otherwise, it’s binary. Note that
this may conflict with the type of file if it’s an open
file object; make sure you do not try to write a string to a
binary stream and vice versa.

QName wrapper. This can be used to wrap a QName attribute value, in order
to get proper namespace handling on output. text_or_uri is a string
containing the QName value, in the form {uri}local, or, if the tag argument
is given, the URI part of a QName. If tag is given, the first argument is
interpreted as a URI, and this argument is interpreted as a local name.
QName instances are opaque.

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, when given,
must be a callable accepting two positional arguments: a tag and
a dict of attributes. It is expected to return a new element instance.

This class is the low-level building block of the module. It uses
xml.parsers.expat for efficient, event-based parsing of XML. It can
be fed XML data incrementally with the feed() method, and parsing
events are translated to a push API - by invoking callbacks on the target
object. If target is omitted, the standard TreeBuilder is used.
The html argument was historically used for backwards compatibility and is
now deprecated. If encoding1 is given, the value overrides the
encoding specified in the XML file.

Deprecated since version 3.4: The html argument. The remaining arguments should be passed via
keyword to prepare for the removal of the html argument.

XMLParser.feed() calls target’s start(tag,attrs_dict) method
for each opening tag, its end(tag) method for each closing tag, and data
is processed by method data(data). XMLParser.close() calls
target’s method close(). XMLParser can be used not only for
building a tree structure. This is an example of counting the maximum depth
of an XML file:

>>> fromxml.etree.ElementTreeimportXMLParser>>> classMaxDepth:# The target object of the parser... maxDepth=0... depth=0... defstart(self,tag,attrib):# Called for each opening tag.... self.depth+=1... ifself.depth>self.maxDepth:... self.maxDepth=self.depth... defend(self,tag):# Called for each closing tag.... self.depth-=1... defdata(self,data):... pass# We do not need to do anything with data.... defclose(self):# Called when all data has been parsed.... returnself.maxDepth...>>> target=MaxDepth()>>> parser=XMLParser(target=target)>>> exampleXml="""... <a>... <b>... </b>... <b>... <c>... <d>... </d>... </c>... </b>... </a>""">>> parser.feed(exampleXml)>>> parser.close()4

A pull parser suitable for non-blocking applications. Its input-side API is
similar to that of XMLParser, but instead of pushing calls to a
callback target, XMLPullParser collects an internal list of parsing
events and lets the user read from it. events is a sequence of events to
report back. The supported events are the strings "start", "end",
"start-ns" and "end-ns" (the “ns” events are used to get detailed
namespace information). If events is omitted, only "end" events are
reported.

Signal the parser that the data stream is terminated. Unlike
XMLParser.close(), this method always returns None.
Any events not yet retrieved when the parser is closed can still be
read with read_events().

Return an iterator over the events which have been encountered in the
data fed to the
parser. The iterator yields (event,elem) pairs, where event is a
string representing the type of event (e.g. "end") and elem is the
encountered Element object.

Events provided in a previous call to read_events() will not be
yielded again. Events are consumed from the internal queue only when
they are retrieved from the iterator, so multiple readers iterating in
parallel over iterators obtained from read_events() will have
unpredictable results.

Note

XMLPullParser only guarantees that it has seen the “>”
character of a starting tag when it emits a “start” event, so the
attributes are defined, but the contents of the text and tail attributes
are undefined at that point. The same applies to the element children;
they may or may not be present.

XML parse error, raised by the various parsing methods in this module when
parsing fails. The string representation of an instance of this exception
will contain a user-friendly error message. In addition, it will have
the following attributes available: