Python Glossary Русский

all Python 3xml.etree.ElementTreefunction

xml.etree.ElementTree.iterparse()

incremental parsing

Parses an XML file incrementally and yields (event, element) pairs — for large files that do not fit in memory at once.

Syntax

for event, elem in ET.iterparse(source, events=None):

iterparse alone saves no memory: the tree keeps growing to the end of the document unless you call elem.clear() on processed elements. On a 'start' event the element's text and children are not read yet, so take content on 'end'. Only 'end' events are reported by default. Reads are blocking; for network data use XMLPullParser. Since 3.15 an unclosed iterator over a file name emits ResourceWarning.

Examples

import xml.etree.ElementTree as ET
import io
data = io.BytesIO(b'<r><i>1</i><i>2</i><i>3</i></r>')
total = 0
for event, elem in ET.iterparse(data):
    if elem.tag == 'i':
        total += int(elem.text)
        elem.clear()
print(total)  # → 6
import xml.etree.ElementTree as ET
import io
it = ET.iterparse(io.BytesIO(b'<r><i/></r>'), events=('start', 'end'))
print([(ev, el.tag) for ev, el in it])
# → [('start', 'r'), ('start', 'i'), ('end', 'i'), ('end', 'r')]
print(it.root.tag)  # → r

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy