Parse large XML to JSON using streaming with lxml iterparse. Read element by element without loading the whole tree into RAM and clear processed elements from memory to keep footprint constant.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's Python code showing how to parse a large XML file element by element with lxml iterparse, convert each element to a dictionary recursively, write JSON incrementally to a file, and clear processed elements to keep memory usage constant.
When you use lxml.etree.iterparse you never have to build the entire tree: you register for the "end" event of the elements you care about, turn those elements into Python objects, and then explicitly clear them and detach them from their parent so the parser can reuse the memory.
A minimal example that streams <record> elements out of a large file into a JSON array could look like this:
python
from lxml import etree
import json
def elem_to_dict(elem):
"""Recursively convert an Element and its children to a dict."""
d = {}
# include attributes if needed
if elem.attrib:
d.update(elem.attrib)
for child in elem:
if len(child): # has grandchildren
d[child.tag] = elem_to_dict(child)
else:
d[child.tag] = child.text
return d
def stream_xml_to_json(xml_path, json_path, record_tag):
context = etree.iterparse(xml_path, events=("end",), tag=record_tag)
with open(json_path, "w", encoding="utf-8") as out:
out.write("[\n")
first = True
for event, elem in context:
# turn the element into a Python structure
record = elem_to_dict(elem)
# write it out as JSON
if not first:
out.write(",\n")
json.dump(record, out, ensure_ascii=False)
first = False
# free the element and its siblings to keep memory constant
elem.clear()
# also remove references to already processed siblings
while elem.getprevious() is not None:
del elem.getparent()[0]
out.write("\n]")
# example usage
stream_xml_to_json("large.xml", "output.json", record_tag="record")
A few important points:
Use the "end" event so you see fully built subtrees for the tag you’re interested in.
Only register for the tag you need with tag=record_tag to avoid building unrelated subtrees.
After processing, call elem.clear() and delete previous siblings with del elem.getparent()[0] to allow lxml to discard those parts of the tree. This keeps the memory footprint roughly constant regardless of the input size.
If you don’t want to wrap the output in a JSON array, you can also make stream_xml_to_json a generator that yields record dicts and handle writing elsewhere.
This pattern lets you process arbitrarily large XML files in a streaming fashion without ever loading the whole document into RAM.