IC Improve Code Recipes

Recipe 12.6 · Python

Streaming Huge XML and JSON Files

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

A nightly feed arrives as a 3 GB XML file with two million <Transaction> elements, or as a JSON array of the same size. Loading it with XDocument.Load or JsonSerializer.Deserialize<List<T>> needs several times the file size in memory. On a shared server the job either fails with OutOfMemoryException or pushes everything else into paging.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Load a whole XML file into memory, materialize a list, then save each item (p273_r12_6_load_whole_xml_then_save_before.py)
"""Load a whole XML file into memory, materialize a list, then save each item

Source: ImproveCode, Chapter 12, Recipe 12.6 "Streaming Huge XML and JSON Files"
Section: The way it's often written
Book page: 273  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
XDocument.Load + Descendants().Select().ToList() -> ET.parse + iter() into a list.
"""

import xml.etree.ElementTree as ET
from collections.abc import Callable
from typing import Any


def import_all(path: str, map: Callable[[ET.Element], Any],
               save: Callable[[Any], None]) -> None:
    # Not to copy: the whole file in memory, then the whole list again
    doc = ET.parse(path)
    transactions = [map(e) for e in doc.iter("Transaction")]
    for t in transactions:
        save(t)

The improved recipe

Stream one record at a time. For XML, move an XmlReader forward and materialize only the current element as a small XElement. For JSON arrays, let the serializer yield items as an IAsyncEnumerable<T>.

Usage, processing in batches of 1,000:

Requirements: Python 3.12+. Install: pip install aiofiles defusedxml ijson pydantic

Python Stream elements from huge XML files and items from huge JSON arrays (p273_r12_6_streaming_xml_json_readers.py)
"""Stream elements from huge XML files and items from huge JSON arrays

Source: ImproveCode, Chapter 12, Recipe 12.6 "Streaming Huge XML and JSON Files"
Section: The improved recipe
Book page: 273-274  -- original C# listing
Converted from C# to Python.
XmlReader + XNode.ReadFrom -> defusedxml iterparse (DTDs forbidden), clearing
each element after it is yielded; DeserializeAsyncEnumerable -> ijson.items_async
over an aiofiles stream, validated with a pydantic TypeAdapter.
"""

from __future__ import annotations

import asyncio
import xml.etree.ElementTree as ET
from collections.abc import AsyncIterator
from typing import TypeVar

import aiofiles
import ijson
from defusedxml.ElementTree import iterparse
from pydantic import TypeAdapter

T = TypeVar("T")


def _local_name(tag: str) -> str:
    return tag.rsplit("}", 1)[-1]


async def read_elements_async(path: str, element_name: str) -> AsyncIterator[ET.Element]:
    context = iterparse(path, events=("start", "end"), forbid_dtd=True)
    depth = 0  # >0 while inside a matching element (handles nesting)
    for event, elem in context:
        if _local_name(elem.tag) != element_name:
            continue
        if event == "start":
            depth += 1
            continue
        depth -= 1
        if depth == 0:
            yield elem
            elem.clear()  # release memory for the processed subtree
            await asyncio.sleep(0)  # cooperative cancellation point


async def read_json_array_async(path: str, item_type: type[T]) -> AsyncIterator[T]:
    adapter: TypeAdapter[T | None] = TypeAdapter(item_type | None)  # type: ignore[operator]
    async with aiofiles.open(path, "rb", buffering=64 * 1024) as stream:
        async for raw in ijson.items_async(stream, "item", use_float=False):
            item = adapter.validate_python(raw)
            if item is not None:
                yield item

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Usage: stream Transaction elements and save them in batches of 1000 (p274_r12_6_batched_streaming_xml_import.py)
"""Usage: stream Transaction elements and save them in batches of 1000

Source: ImproveCode, Chapter 12, Recipe 12.6 "Streaming Huge XML and JSON Files"
Section: The improved recipe
Book page: 274-275  -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; streaming reader from p273. `await foreach`
-> `async for`; Transaction.from_xml and repository are supplied by the caller.
"""

from __future__ import annotations

from typing import Any

from p273_r12_6_streaming_xml_json_readers import read_elements_async


async def import_transactions(path: str, transaction_type: Any,
                              repository: Any) -> None:
    batch: list[Any] = []
    async for e in read_elements_async(path, "Transaction"):
        batch.append(transaction_type.from_xml(e))
        if len(batch) == 1000:
            await repository.save_batch_async(batch)
            batch.clear()
    if batch:
        await repository.save_batch_async(batch)

How it works

XmlReader is a forward-only cursor over the file. It holds a small buffer, not a tree. The loop moves through nodes until it lands on a start tag with the name you want, then hands the reader to XNode.ReadFromAsync, which reads exactly that element and its children into an XElement. You get the convenience of LINQ to XML for one record and the memory profile of a cursor for the file. Once your code drops the element, it is garbage.

The comment in the loop marks the classic bug. ReadFrom already advances the reader past the end tag. If you call Read again, you skip the next sibling, and with IgnoreWhitespace on, that sibling is the next record. The symptom is a job that processes exactly half the file and reports success.

DeserializeAsyncEnumerable<T> does the same for a JSON document whose root is an array. It reads the stream in buffers and yields each element as soon as it is complete. Combined with await foreach and batched database writes (see Chapter 1 for SqlBulkCopy), memory stays flat no matter how large the file is.

I tested both readers on generated files of 200,000 records each. The XML reader returned every record, with no skipped siblings, and the JSON reader matched the record count and the totals of the source data.

Variations and pitfalls

  • JSON arrays inside an object. DeserializeAsyncEnumerable handles a root-level array. For { "transactions": [ ... ] }, either ask the producer for JSON Lines (one object per line, read with StreamReader.ReadLineAsync and JsonSerializer.Deserialize) or, on .NET 9, use the topLevelValues overload for newline-delimited documents. A hand-written Utf8JsonReader loop is the last resort.
  • Typed records from XML. If each element maps to an XmlSerializer class, call serializer.Deserialize(reader.ReadSubtree()) instead of XNode.ReadFromAsync, with the serializer cached as in Recipe 12.3.
  • Compressed feeds. Wrap the file stream in GZipStream and pass that to XmlReader.Create or the JSON reader. Nothing else changes.
  • Progress and restart. Log the record count every 50,000 records, and store the last committed record key. A job that fails at record 1.8 million should not start again from zero.