Python ElementTree
last modified November 30, 2026 Python 3.15
In this article we show how to parse, query, create, and modify XML
documents with the xml.etree.ElementTree module.
ElementTree is the main XML API of the Python standard library. It loads
a whole document into memory as a tree of Element objects.
Each element has a tag, a dictionary of attributes, text, and a list of
child elements, which behave much like a Python list. The module is
implemented in C and is fast enough for most everyday XML work.
The standard library has two other XML APIs. The event-based SAX parser streams a document without building a tree, and minidom implements the W3C DOM interface known from other languages. The third-party lxml library offers the ElementTree API with full XPath, XSLT, and schema validation.
By convention the module is imported under the short name
ET.
Parsing a string
The fromstring function parses XML text and returns the
root element of the document.
import xml.etree.ElementTree as ET
data = """<languages>
<language>Python</language>
<language>Ada</language>
<language>Fortran</language>
</languages>"""
root = ET.fromstring(data)
print(root.tag)
for child in root:
print(child.tag, child.text)
The program parses a small document with three
language elements.
root = ET.fromstring(data) print(root.tag)
The tag attribute holds the name of the element.
for child in root:
print(child.tag, child.text)
Iterating over an element yields its direct children. The
text attribute is the text that directly follows the
opening tag.
$ python first.py languages language Python language Ada language Fortran
Parsing a file
The parse function reads a file and returns an
ElementTree object, which wraps the whole document. We use
the following file in the rest of the article.
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product id="1" category="drinks">
<name>Green tea</name>
<price>4.50</price>
<quantity>30</quantity>
</product>
<product id="2" category="drinks">
<name>Coffee</name>
<price>7.90</price>
<quantity>12</quantity>
</product>
<product id="3" category="food">
<name>Rye bread</name>
<price>2.20</price>
<quantity>0</quantity>
</product>
<product id="4" category="food">
<name>Honey</name>
<price>6.75</price>
<quantity>8</quantity>
</product>
<product id="5" category="drinks">
<name>Cocoa</name>
<price>5.10</price>
<quantity>0</quantity>
</product>
</products>
Each product has two attributes, id and
category, and three child elements.
import xml.etree.ElementTree as ET
tree = ET.parse('products.xml')
root = tree.getroot()
print(f'{len(root)} products')
for product in root.findall('product'):
pid = product.get('id')
name = product.findtext('name')
price = float(product.findtext('price'))
qty = int(product.findtext('quantity'))
print(f'{pid:>2} {name:<10} {price:6.2f} {qty:4}')
The program prints the products as a table.
tree = ET.parse('products.xml')
root = tree.getroot()
The getroot method returns the root element. The
parse function also accepts an open file object.
print(f'{len(root)} products')
The len function returns the number of direct children.
for product in root.findall('product'):
pid = product.get('id')
name = product.findtext('name')
price = float(product.findtext('price'))
The findall method returns a list of matching children.
The get method reads an attribute and
findtext returns the text of the first matching child.
XML has no data types; all values are strings, so we convert the price
and the quantity ourselves.
$ python read_file.py 5 products 1 Green tea 4.50 30 2 Coffee 7.90 12 3 Rye bread 2.20 0 4 Honey 6.75 8 5 Cocoa 5.10 0
Text and tail
In documents with mixed content, text is not stored in one place.
ElementTree splits it between the text and the
tail attributes.
import xml.etree.ElementTree as ET
data = '<p class="note">Read <b>this</b> twice.<br/>Then act.</p>'
p = ET.fromstring(data)
print('tag:', p.tag)
print('attrib:', p.attrib)
print('text:', repr(p.text))
for child in p:
print(child.tag, repr(child.text), repr(child.tail))
print('all text:', ''.join(p.itertext()))
The paragraph contains text, a b element, more text, an
empty br element, and the final sentence.
print('attrib:', p.attrib)
The attrib attribute is a plain dictionary of the element's
attributes.
for child in p:
print(child.tag, repr(child.text), repr(child.tail))
The text of an element is the text before its first child.
The text after a child's closing tag belongs to that child as its
tail. So ' twice.' is the tail of
b, and 'Then act.' is the tail of
br. When an element has no text, the attribute is
None.
print('all text:', ''.join(p.itertext()))
The itertext method yields all text and tail pieces inside
the element in document order.
$ python element_parts.py
tag: p
attrib: {'class': 'note'}
text: 'Read '
b 'this' ' twice.'
br None 'Then act.'
all text: Read this twice.Then act.
Finding elements
ElementTree has several methods for locating elements. They differ in how deep they search and in what they return.
import xml.etree.ElementTree as ET
root = ET.parse('products.xml').getroot()
first = root.find('product')
print('first:', first.findtext('name'))
names = root.findall('name')
print('name children of root:', len(names))
names = [e.text for e in root.iter('name')]
print('iter:', names)
discount = first.find('discount')
print('discount element:', discount)
print('discount text:', first.findtext('discount', default='none'))
if discount is not None:
print('the product has a discount')
The program compares find, findall,
iter, and findtext.
first = root.find('product')
The find method returns the first matching child, or
None.
names = root.findall('name')
print('name children of root:', len(names))
A plain tag name in find and findall matches
only direct children. The name elements are grandchildren
of the root, so the list is empty.
names = [e.text for e in root.iter('name')]
The iter method walks the whole subtree, including the
element itself, and yields every element with the given tag.
print('discount text:', first.findtext('discount', default='none'))
if discount is not None:
print('the product has a discount')
The findtext method returns the default value
when the element does not exist. When checking the result of
find, compare it with None. An
if discount: test would be wrong: the truth value of an
element depends on whether it has children, and Python emits a
DeprecationWarning for it.
$ python finding.py first: Green tea name children of root: 0 iter: ['Green tea', 'Coffee', 'Rye bread', 'Honey', 'Cocoa'] discount element: None discount text: none
ElementPath expressions
The find family of methods accepts ElementPath, a small
subset of XPath. It supports descendants, the parent step, attribute
and child predicates, and positions.
import xml.etree.ElementTree as ET
root = ET.parse('products.xml').getroot()
def show(path):
found = root.findall(path)
print(f'{path:<26}', [e.get('id') or e.text for e in found])
show('product')
show('.//name')
show("product[@category='food']")
show("product[quantity='0']")
show('product[name]')
show('product[1]')
show('product[last()]')
show('product[last()-1]')
show(".//name[.='Honey']/..")
The show function prints the id attribute of
each match, or its text for elements without an id.
show('.//name')
The .// prefix selects matching elements at any depth below
the current element.
show("product[@category='food']")
show("product[quantity='0']")
show('product[name]')
Predicates filter the matches: [@attr='value'] tests an
attribute, [tag='text'] tests the text of a child, and
[tag] requires that a child exists.
show('product[1]')
show('product[last()]')
show('product[last()-1]')
Positions start at 1. The last() function refers to the
last element.
show(".//name[.='Honey']/..")
The . predicate tests the text of the element itself, and
.. selects the parent. Here we find the product whose name
is Honey. ElementPath does not support functions such as
contains or arithmetic; for full XPath, see the
lxml article.
$ python paths.py product ['1', '2', '3', '4', '5'] .//name ['Green tea', 'Coffee', 'Rye bread', 'Honey', 'Cocoa'] product[@category='food'] ['3', '4'] product[quantity='0'] ['3', '5'] product[name] ['1', '2', '3', '4', '5'] product[1] ['1'] product[last()] ['5'] product[last()-1] ['4'] .//name[.='Honey']/.. ['4']
Building a document
New documents are built from Element and
SubElement objects.
import xml.etree.ElementTree as ET
root = ET.Element('products')
product = ET.SubElement(root, 'product', id='1')
ET.SubElement(product, 'name').text = 'Green tea'
ET.SubElement(product, 'price').text = '4.50'
product = ET.SubElement(root, 'product')
product.set('id', '2')
ET.SubElement(product, 'name').text = 'Coffee'
ET.SubElement(product, 'price').text = str(7.9)
print(ET.tostring(root, encoding='unicode'))
The program creates a root with two products and serializes it.
product = ET.SubElement(root, 'product', id='1') ET.SubElement(product, 'name').text = 'Green tea'
The SubElement function creates an element and appends it
to the parent in one step. Keyword arguments become attributes. The
function returns the new element, so we can set its text right away.
product.set('id', '2')
...
ET.SubElement(product, 'price').text = str(7.9)
The set method adds an attribute to an existing element.
Text and attribute values must be strings; numbers have to be
converted first.
print(ET.tostring(root, encoding='unicode'))
The tostring function serializes an element. Without
encoding='unicode' it returns bytes. The
output has no line breaks, because we have not added any whitespace to
the tree.
$ python create.py <products><product id="1"><name>Green tea</name><price>4.50</price></product><product id="2"><name>Coffee</name><price>7.9</price></product></products>
Indenting and writing a file
The indent function adds whitespace to the tree, and the
write method of ElementTree saves the
document to a file.
import xml.etree.ElementTree as ET
items = [
('1', 'Green tea', 4.5, 30),
('2', 'Coffee', 7.9, 12),
('3', 'Rye bread', 2.2, 0),
]
root = ET.Element('products')
for pid, name, price, qty in items:
product = ET.SubElement(root, 'product', id=pid)
ET.SubElement(product, 'name').text = name
ET.SubElement(product, 'price').text = f'{price:.2f}'
ET.SubElement(product, 'quantity').text = str(qty)
ET.indent(root)
tree = ET.ElementTree(root)
tree.write('stock.xml', encoding='utf-8', xml_declaration=True)
with open('stock.xml', encoding='utf-8') as f:
print(f.read())
The program creates the products from a list of tuples and writes them
to stock.xml.
ET.SubElement(product, 'price').text = f'{price:.2f}'
We format the price with two decimal places before storing it.
ET.indent(root)
The indent function modifies the tree in place: it sets
the text and tail of the elements to newlines
and spaces. The default indentation is two spaces; the
space parameter changes it.
tree = ET.ElementTree(root)
tree.write('stock.xml', encoding='utf-8', xml_declaration=True)
We wrap the root in an ElementTree and write it with an
XML declaration. ElementTree writes the declaration with single quotes,
which is valid XML.
$ python write_file.py
<?xml version='1.0' encoding='utf-8'?>
<products>
<product id="1">
<name>Green tea</name>
<price>4.50</price>
<quantity>30</quantity>
</product>
<product id="2">
<name>Coffee</name>
<price>7.90</price>
<quantity>12</quantity>
</product>
<product id="3">
<name>Rye bread</name>
<price>2.20</price>
<quantity>0</quantity>
</product>
</products>
Escaping special characters
The characters <, &, and quotes have a
special meaning in XML. ElementTree escapes them when writing and
unescapes them when parsing.
import xml.etree.ElementTree as ET
note = ET.Element('note', title='Tom & Jerry "classic"')
note.text = 'if a < b and b > c: print("ok")'
data = ET.tostring(note, encoding='unicode')
print(data)
parsed = ET.fromstring(data)
print(parsed.get('title'))
print(parsed.text)
The program stores a title and a piece of code in an element.
note = ET.Element('note', title='Tom & Jerry "classic"')
note.text = 'if a < b and b > c: print("ok")'
We assign plain strings and never escape anything by hand. Escaping a
value ourselves would escape it twice, producing &
in the file.
parsed = ET.fromstring(data)
print(parsed.get('title'))
After parsing, the values are the original strings again.
$ python escaping.py
<note title="Tom & Jerry "classic"">if a < b and b > c: print("ok")</note>
Tom & Jerry "classic"
if a < b and b > c: print("ok")
Modifying a document
A parsed tree can be changed and written back. In the next example we raise all prices, remove the products that are out of stock, insert a new product, and change an attribute.
import xml.etree.ElementTree as ET
tree = ET.parse('products.xml')
root = tree.getroot()
for price in root.iter('price'):
raised = float(price.text) * 1.1
price.text = f'{raised:.2f}'
for product in root.findall("product[quantity='0']"):
root.remove(product)
milk = ET.Element('product', id='6', category='drinks')
ET.SubElement(milk, 'name').text = 'Milk'
ET.SubElement(milk, 'price').text = '1.30'
ET.SubElement(milk, 'quantity').text = '24'
root.insert(0, milk)
root.find("product[@id='4']").set('category', 'sweets')
tree.write('updated.xml', encoding='utf-8', xml_declaration=True)
for product in ET.parse('updated.xml').getroot():
print(product.get('id'), product.get('category'),
product.findtext('name'), product.findtext('price'))
The program writes the modified document to updated.xml
and then reads it back.
for price in root.iter('price'):
raised = float(price.text) * 1.1
price.text = f'{raised:.2f}'
Changing an element's text is a simple assignment.
for product in root.findall("product[quantity='0']"):
root.remove(product)
The remove method deletes a direct child. It is safe here,
because findall returns a new list, not a live view of the
children.
milk = ET.Element('product', id='6', category='drinks')
...
root.insert(0, milk)
An element created with Element is not part of any tree.
The insert method places it at the given index;
append would add it at the end.
root.find("product[@id='4']").set('category', 'sweets')
The set method replaces the value of an existing attribute.
$ python modify.py 6 drinks Milk 1.30 1 drinks Green tea 4.95 2 drinks Coffee 8.69 4 sweets Honey 7.43
Removing elements while iterating
Removing children while iterating directly over the parent skips elements, just as it does with a list.
import xml.etree.ElementTree as ET
data = '<a><x/><x/><x/><y/></a>'
root = ET.fromstring(data)
for child in root:
if child.tag == 'x':
root.remove(child)
print(ET.tostring(root, encoding='unicode'))
root = ET.fromstring(data)
for child in list(root):
if child.tag == 'x':
root.remove(child)
print(ET.tostring(root, encoding='unicode'))
We try to remove all three x elements twice.
for child in root:
if child.tag == 'x':
root.remove(child)
When the first x is removed, the others move one position
to the left and the loop steps over the second one. One x
element survives.
for child in list(root):
Iterating over a copy of the children fixes the problem. Note that
tostring writes empty elements as <x />;
the short_empty_elements=False option writes
<x></x> instead.
$ python remove_pitfall.py <a><x /><y /></a> <a><y /></a>
Namespaces
Elements in a namespace have the namespace URI in their tag, in the
form {uri}name. The prefixes used in the file are not
kept. We use the following feed with a default namespace and a
media prefix.
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/">
<title>Release notes</title>
<entry>
<title>Version 2.1</title>
<media:thumbnail url="v21.png"/>
</entry>
<entry>
<title>Version 2.0</title>
<media:thumbnail url="v20.png"/>
</entry>
</feed>
Every element in the file is in the Atom namespace, except
thumbnail, which belongs to the media namespace.
import xml.etree.ElementTree as ET
root = ET.parse('feed.xml').getroot()
print(root.tag)
print('without namespace:', root.findall('entry'))
ns = {
'atom': 'http://www.w3.org/2005/Atom',
'media': 'http://search.yahoo.com/mrss/',
}
for entry in root.findall('atom:entry', ns):
title = entry.findtext('atom:title', namespaces=ns)
thumb = entry.find('media:thumbnail', ns)
print(title, thumb.get('url'))
print([e.text for e in root.findall('.//{*}title')])
The program reads the entries of the feed.
print(root.tag)
print('without namespace:', root.findall('entry'))
The root tag contains the full namespace URI. A search for a plain
entry finds nothing, because no element has that tag.
ns = {
'atom': 'http://www.w3.org/2005/Atom',
'media': 'http://search.yahoo.com/mrss/',
}
for entry in root.findall('atom:entry', ns):
The find methods accept a dictionary that maps our own
prefixes to namespace URIs. The prefixes do not have to match the ones
in the file; a default namespace also needs a prefix here.
print([e.text for e in root.findall('.//{*}title')])
The {*} wildcard matches a tag in any namespace. It works
in the find methods, but not in iter.
$ python namespaces.py
{http://www.w3.org/2005/Atom}feed
without namespace: []
Version 2.1 v21.png
Version 2.0 v20.png
['Release notes', 'Version 2.1', 'Version 2.0']
Writing namespaces
When serializing, ElementTree invents prefixes such as
ns0 for namespaces it does not know. The
register_namespace function sets the prefix to use.
import xml.etree.ElementTree as ET
ATOM = 'http://www.w3.org/2005/Atom'
def make_feed():
feed = ET.Element(f'{{{ATOM}}}feed')
entry = ET.SubElement(feed, f'{{{ATOM}}}entry')
ET.SubElement(entry, f'{{{ATOM}}}title').text = 'Version 2.2'
ET.indent(feed)
return feed
print(ET.tostring(make_feed(), encoding='unicode'))
ET.register_namespace('', ATOM)
print(ET.tostring(make_feed(), encoding='unicode'))
The program serializes the same feed before and after registering the Atom namespace.
feed = ET.Element(f'{{{ATOM}}}feed')
Namespaced elements are created with the full {uri}name
tag. In an f-string, the doubled braces produce literal braces around
the URI.
ET.register_namespace('', ATOM)
An empty prefix makes Atom the default namespace. The registration is global and affects every later serialization in the program.
$ python write_namespaces.py
<ns0:feed xmlns:ns0="http://www.w3.org/2005/Atom">
<ns0:entry>
<ns0:title>Version 2.2</ns0:title>
</ns0:entry>
</ns0:feed>
<feed xmlns="http://www.w3.org/2005/Atom">
<entry>
<title>Version 2.2</title>
</entry>
</feed>
Parsing large files
The parse function keeps the whole document in memory. For
large files, iterparse reports elements as they are read,
and we can discard each one after processing it.
import xml.etree.ElementTree as ET
def create_orders(path, count):
with open(path, 'w', encoding='utf-8') as f:
f.write('<orders>\n')
for i in range(1, count + 1):
f.write(f' <order id="{i}"><total>{i % 50}.99</total></order>\n')
f.write('</orders>\n')
create_orders('orders.xml', 200_000)
count = 0
revenue = 0.0
with open('orders.xml', 'rb') as f:
context = ET.iterparse(f, events=('start', 'end'))
event, root = next(context)
for event, elem in context:
if event == 'end' and elem.tag == 'order':
count += 1
revenue += float(elem.findtext('total'))
root.clear()
print(f'{count} orders, revenue {revenue:,.2f}')
print('elements kept in memory:', len(root))
The program first generates a file with 200,000 orders and then sums their totals.
with open('orders.xml', 'rb') as f:
context = ET.iterparse(f, events=('start', 'end'))
event, root = next(context)
The iterparse function returns an iterator of
(event, element) pairs. The first event is the start of
the root element, which we keep. We pass an open file, so the
with statement closes it even if the loop ends early.
if event == 'end' and elem.tag == 'order':
count += 1
revenue += float(elem.findtext('total'))
root.clear()
At the end event, the element and all its children are
complete. After using the order, we clear the root, which drops the
processed orders from the tree. Without this, iterparse
would build the entire tree just like parse.
$ python large_file.py 200000 orders, revenue 5,098,000.00 elements kept in memory: 0
Parse errors
Malformed XML raises ParseError. Its
position attribute is a (line, column) tuple
with a zero-based column.
import xml.etree.ElementTree as ET
documents = [
'<a><b>text</b></a>',
'<a><b>text</a>',
'<a>Tom & Jerry</a>',
'<a></a><b></b>',
]
for doc in documents:
try:
root = ET.fromstring(doc)
print('ok:', root.tag)
except ET.ParseError as e:
line, column = e.position
print(doc)
print(' ' * column + '^', e)
The program parses one correct and three malformed documents and marks the position of each error.
line, column = e.position
print(doc)
print(' ' * column + '^', e)
We print a caret under the character where the parser stopped. An unescaped ampersand, a wrong closing tag, and a second root element are typical errors.
The parser does not load external entities, but untrusted documents can still cause problems, for example by expanding nested entities. See the XML security section of the documentation before parsing data from unknown sources.
$ python errors.py
ok: a
<a><b>text</a>
^ mismatched tag: line 1, column 12
<a>Tom & Jerry</a>
^ not well-formed (invalid token): line 1, column 8
<a></a><b></b>
^ junk after document element: line 1, column 7
Comparing documents
Two documents can have the same content but different text: attribute
order, quotes, whitespace inside tags, and empty element syntax may
vary. The canonicalize function converts a document to the
canonical form C14N 2.0.
import xml.etree.ElementTree as ET a = '<item b="2" a="1"><name>Tea</name><empty/></item>' b = "<item a='1' b='2'><name>Tea</name><empty></empty></item>" print(a == b) print(ET.canonicalize(a)) print(ET.canonicalize(b)) print(ET.canonicalize(a) == ET.canonicalize(b))
The two strings describe the same element.
print(ET.canonicalize(a) == ET.canonicalize(b))
In canonical form, attributes are sorted, double quotes are used, and empty elements get an end tag. The canonical forms are equal, so they can be compared as strings.
$ python compare.py False <item a="1" b="2"><name>Tea</name><empty></empty></item> <item a="1" b="2"><name>Tea</name><empty></empty></item> True
Source
xml.etree.ElementTree – The ElementTree XML API, XML security
In this article we have parsed XML from strings and files, read tags,
attributes, text and tail, searched documents with ElementPath, built,
indented, written, and modified documents, worked with namespaces,
processed a large file with iterparse, handled parse
errors, and compared documents in canonical form. See also
Python XML SAX,
Python XML minidom, and
Python lxml.
Author
List all Python tutorials.