Parse Large XML Incrementally with iterparse
Read a large XML document without loading it whole, yield one record at a time, and clear processed elements to free memory.
Code
import xml.etree.ElementTree as ET
from collections.abc import Iterator
from pathlib import Path
def iter_records(path: Path, tag: str = "record") -> Iterator[dict[str, str]]:
context = ET.iterparse(path, events=("end",))
for _, element in context:
if element.tag != tag:
continue
record = {
child.tag: (child.text or "").strip() for child in element
}
yield record
element.clear()
def write_fixture(path: Path) -> None:
path.write_text(
"<catalog>"
"<record><id>1</id><name>Ada</name></record>"
"<record><id>2</id><name>Grace</name></record>"
"</catalog>",
encoding="utf-8",
)
if __name__ == "__main__":
fixture = Path("catalog.xml")
write_fixture(fixture)
try:
print(list(iter_records(fixture)))
finally:
fixture.unlink()
How it works
Parse Large XML Incrementally with iterparse is built around the functions iter_records and write_fixture.
The file repeats itself only inside for _, element in context. From xml it pulls Iterator, Path — the imports name exactly which library surface the snippet touches.
Points of care
- Plan for an install step:
xmlis a real dependency, resolved by the package manager.
Putting it to use
Entry signature: def iter_records(path: Path, tag: str = "record") -> Iterator[dict[str, str]]
Core lines
def write_fixture(path: Path) -> None:
path.write_text(
"<catalog>"
"<record><id>1</id><name>Ada</name></record>"
"<record><id>2</id><name>Grace</name></record>"
"</catalog>",
encoding="utf-8",
)
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.XML FormatterRe-indent minified or messy XML into a readable structure, validating that every opening tag has a matching closing tag.XML to JSON ConverterConvert XML to JSON, mapping attributes to @ keys, repeated children to arrays, and text content to #text.
FAQ
- Does this require external packages?
- Yes — `xml`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.