Python Glossary Русский

all Python 3xml.etree.ElementTreeterm

xml.etree.ElementTree.Element

tree and elements

A node of the XML tree: a tag name, an attrib dict, text and tail. It behaves like a list of children and searches with find/findall/iter.

Syntax

elem = ET.Element(tag, attrib={}, **extra)
elem.find(path) / elem.findall(path) / elem.iter(tag=None)

find() searches direct children only, findall('.//x') goes to any depth, and iter('x') walks the whole subtree including the element itself. XPath support is limited: [@attr='v'], [tag='text'], [1], [last()] and '..' work, but text(), count() and > < comparisons do not, and a path starting with // raises SyntaxError. Do not write if root.find('x'): an element without children is falsy, and since 3.12 the test also emits DeprecationWarning; compare with None. remove() drops the child together with its tail.

Examples

import xml.etree.ElementTree as ET
x = '<lib><book y="2001"><t>A</t></book><shelf><book y="1999"><t>B</t></book></shelf></lib>'
r = ET.fromstring(x)
print(len(r.findall('book')), len(r.findall('.//book')))  # → 1 2
print([b.get('y') for b in r.iter('book')])  # → ['2001', '1999']
print(r.find(".//book[@y='1999']/t").text)  # → B
print(r.findtext('nope', 'нет'), r.find('nope'))  # → нет None
import xml.etree.ElementTree as ET
r = ET.fromstring('<a><b/></a>')
try:
    r.findall('//b')
except SyntaxError as e:
    print(e)  # → cannot use absolute path on element
print(r.find('b') is not None)  # → True — так, а не if r.find('b'):

See also

Open in the full glossarydocs.python.orgReport an inaccuracy