This is a great question about handling large XML files efficiently using Python. The user wants to:
- Parse large XML files
- Use streaming approach with lxml.etree.iterparse
- Process element by element
- Clear processed elements from memory
- Keep a constant memory footprint
I'll provide a comprehensive solution with multiple examples:
- Basic streaming parser
- Converting to JSON
- Memory cleanup
- Advanced examples with different XML structures
Let me create a complete, production-ready solution:
import json
from lxml import etree
from typing import Generator, Dict, Any
import gc
def xml_to_json_stream(xml_file: str, target_element: str, output_file: str = None, chunk_size: int = 100):
"""
Parse large XML file and convert to JSON using streaming.
Processes elements one at a time and clears memory after each chunk.
Args:
xml_file: Path to XML file
target_element: XML element tag to process (e.g., 'record', 'item')
output_file: Optional file to write JSON results
chunk_size: Process and write every N elements
"""
records = []
count = 0
try:
context = etree.iterparse(xml_file, events=('end',), recover=True)
for event, element in context:
if element.tag == target_element:
# Convert element to JSON
record = element_to_dict(element)
records.append(record)
count += 1
# Clear the element from memory
element.clear()
# Also clear preceding siblings
while element.getprevious() is not None:
del element.getparent()[0]
# Write to file periodically and clear memory
if count % chunk_size == 0:
if output_file:
write_json_batch(output_file, records, count == chunk_size)
else:
print(f"Processed {count} records")
records = []
gc.collect()
# Write remaining records
if records and output_file:
write_json_batch(output_file, records, False)
print(f"Total records processed: {count}")
except Exception as e:
print(f"Error parsing XML: {e}")
raise
def element_to_dict(element) -> Dict[str, Any]:
I'm building a streaming XML parser that processes elements in batches, writing results periodically and forcing garbage collection to maintain constant memory usage. The function iterates through target elements, converts them to dictionaries, clears them from memory, and flushes accumulated records to a file at regular intervals.
The element_to_dict function recursively transforms XML elements into JSON-compatible dictionaries by extracting attributes, text content, and child elements. When multiple children share the same tag, it automatically converts them into a list to preserve all data. The write_json_batch function handles streaming JSON output by appending records to a file with proper formatting and comma placement.
For the example usage, I'm calling xml_to_json_stream to process a large XML file, extracting 'record' elements in chunks of 100 and writing the results to output.json.
Streaming XML to JSON Parser with Memory Management
Here's a comprehensive solution for parsing large XML files efficiently:
Basic Streaming Parser
import json
from lxml import etree
from typing import Generator, Dict, Any
import gc
from pathlib import Path
class StreamingXMLParser:
"""
Efficiently parse large XML files and convert to JSON
with constant memory footprint.
"""
def __init__(self, xml_file: str, chunk_size: int = 100):
self.xml_file = xml_file
self.chunk_size = chunk_size
self.count = 0
def element_to_dict(self, element) -> Dict[str, Any]:
"""Convert XML element to dictionary recursively."""
result = {}
# Add attributes with @ prefix
if element.attrib:
for key, value in element.attrib.items():
result[f"@{key}"] = value
# Add text content
text = element.text.strip() if element.text else ""
# Process children
children_dict = {}
for child in element:
child_data = self.element_to_dict(child)
# Handle multiple elements with same tag
if child.tag in children_dict:
if not isinstance(children_dict[child.tag], list):
children_dict[child.tag] = [children_dict[child.tag]]
children_dict[child.tag].append(child_data)
else:
children_dict[child.tag] = child_data
# Combine text and children
if text and children_dict:
result['#text'] = text
result.update(children_dict)
elif children_dict:
result.update(children_dict)
elif text:
return text if len(result) == 0 else {**result, '#text': text}
return result if result else None
def parse(self, target_elements: list) -> Generator[Dict, None, None]:
"""
Stream parse XML, yielding processed elements.
Args:
target_elements: List of element tags to extract
Yields:
Dictionary representation of each matching element
"""
try:
# Use iterparse for memory-efficient streaming
context = etree.iterparse(
self.xml_file,
events=('end',),
recover=True, # Recover from errors
huge_tree=True # Handle large trees
)
for event, element in context:
if element.tag in target_elements:
# Convert to dict
data = self.element_to_dict(element)
self.count += 1
# Clear element from memory immediately
self._clear_element(element)
yield data
# Periodic garbage collection
if self.count % self.chunk_size == 0:
gc.collect()
except Exception as e:
print(f"❌ Parse error: {e}")
raise
@staticmethod
def _clear_element(element):
"""Remove element and its siblings from memory."""
element.clear()
while element.getprevious() is not None:
del element.getparent()[0]
def parse_to_file(self, target_elements: list, output_file: str):
"""Parse XML and write JSON array to file."""
with open(output_file, 'w') as f:
f.write('[\n')
for i, record in enumerate(self.parse(target_elements)):
json.dump(record, f, indent=2)
f.write(',\n')
# Replace last comma with closing bracket
f.seek(f.tell() - 2)
f.write('\n]')
print(f"✅ Processed {self.count} records → {output_file}")
Advanced Usage with Filtering
class FilteredXMLParser(StreamingXMLParser):
"""Extended parser with filtering and transformation."""
def parse_filtered(self, target_elements: list,
filter_func=None,
transform_func=None) -> Generator[Dict, None, None]:
"""
Parse with optional filtering and transformation.
Args:
target_elements: Tags to extract
filter_func: Function(element) -> bool to filter records
transform_func: Function(dict) -> dict to transform records
"""
for element_dict in self.parse(target_elements):
# Apply filter if provided
if filter_func and not filter_func(element_dict):
continue
# Apply transformation if provided
if transform_func:
element_dict = transform_func(element_dict)
yield element_dict
Practical Examples
Example 1: Basic Usage
# Simple XML to JSON conversion
parser = StreamingXMLParser('large_data.xml', chunk_size=50)
parser.parse_to_file(['record', 'item'], 'output.json')
# Or stream directly
for record in parser.parse(['record']):
process_record(record)
Example 2: Large E-commerce Catalog
<!-- products.xml (millions of records) -->
<?xml version="1.0"?>
<catalog>
<product id="1">
<name>Laptop</name>
<price currency="USD">999.99</price>
<stock>150</stock>
</product>
<!-- Many more products -->
</catalog>
def filter_in_stock(product):
return product.get('stock', 0) > 0
def add_category(product):
product['category'] = 'Electronics'
product['price'] = float(product['price'].split()[0])
return product
parser = FilteredXMLParser('products.xml', chunk_size=200)
with open('active_products.json', 'w') as f:
f.write('[\n')
count = 0
for product in parser.parse_filtered(
['product'],
filter_func=filter_in_stock,
transform_func=add_category
):
json.dump(product, f, indent=2)
f.write(',\n')
count += 1
f.seek(f.tell() - 2)
f.write('\n]')
print(f"Processed {count} active products")
Example 3: Database Import
import sqlite3
from collections import defaultdict
class XMLToDatabase:
"""Stream XML directly into database."""
def __init__(self, db_path: str, batch_size: int = 1000):
self.db_path = db_path
self.batch_size = batch_size
def import_xml(self, xml_file: str, target_element: str, table_name: str):
"""Import XML directly to SQLite."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
parser = StreamingXMLParser(xml_file, chunk_size=self.batch_size)
batch = []
columns_created = False
for record in parser.parse([target_element]):
batch.append(record)
# Create table on first record
if not columns_created:
self._create_table(cursor, table_name, record)
columns_created = True
# Insert batch
if len(batch) >= self.batch_size:
self._insert_batch(cursor, table_name, batch)
conn.commit()
batch = []
gc.collect()
# Insert remaining records
if batch:
self._insert_batch(cursor, table_name, batch)
conn.commit()
conn.close()
print(f"✅ Imported {parser.count} records to {table_name}")
def _create_table(self, cursor, table_name: str, sample_record: dict):
"""Create table schema from sample record."""
columns = []
for key, value in sample_record.items():
col_type = self._infer_type(value)
columns.append(f"{key} {col_type}")
create_sql = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {', '.join(columns)})"
cursor.execute(create_sql)
def _insert_batch(self, cursor, table_name: str, batch: list):
"""Insert batch of records."""
if not batch:
return
columns = list(batch[0].keys())
placeholders = ', '.join(['?' for _ in columns])
insert_sql = f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES ({placeholders})"
values = [tuple(record.get(col) for col in columns) for record in batch]
cursor.executemany(insert_sql, values)
@staticmethod
def _infer_type(value):
"""Infer SQL type from Python value."""
if isinstance(value, int):
return 'INTEGER'
elif isinstance(value, float):
return 'REAL'
else:
return 'TEXT'
# Usage
importer = XMLToDatabase('data.db', batch_size=1000)
importer.import_xml('huge_export.xml', 'record', 'records_table')
Example 4: Streaming with Validation
from dataclasses import dataclass
from typing import Optional
@dataclass
class Product:
id: str
name: str
price: float
@classmethod
def from_dict(cls, data: dict):
try:
return cls(
id=data['id'],
name=data.get('name', ''),
price=float(data.get('price', 0))
)
except (KeyError, ValueError) as e:
raise ValueError(f"Invalid product data: {e}")
class ValidatingXMLParser(StreamingXMLParser):
"""Parse and validate XML records."""
def parse_and_validate(self, target_elements: list, model_class):
"""Parse and validate against data model."""
errors = []
valid_count = 0
for record_dict in self.parse(target_elements):
try:
record = model_class.from_dict(record_dict)
yield record
valid_count += 1
except Exception as e:
errors.append({'record': record_dict, 'error': str(e)})
if errors:
print(f"⚠️ {len(errors)} validation errors")
with open('validation_errors.json', 'w') as f:
json.dump(errors, f, indent=2)
print(f"✅ {valid_count} valid records processed")
# Usage
parser = ValidatingXMLParser('products.xml')
for product in parser.parse_and_validate(['product'], Product):
print(f"Valid: {product.name} - ${product.price}")
Memory Efficiency Comparison
import psutil
import os
def monitor_memory(func):
"""Decorator to monitor memory usage."""
def wrapper(*args, **kwargs):
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024 / 1024 # MB
result = func(*args, **kwargs)
mem_after = process.memory_info().rss / 1024 / 1024
print(f"Memory used: {mem_before:.2f}MB → {mem_after:.2f}MB (Δ {mem_after - mem_before:+.2f}MB)")
return result
return wrapper
@monitor_memory
def parse_streaming():
"""Streaming approach - constant memory."""
parser = StreamingXMLParser('huge_file.xml', chunk_size=100)
count = 0
for _ in parser.parse(['record']):
count += 1
return count
@monitor_memory
def parse_traditional():
"""Traditional approach - loads entire tree."""
tree = etree.parse('huge_file.xml')
count = len(tree.xpath('//record'))
return count
# Streaming: 2-5 MB
# Traditional: 500-2000 MB (depending on file size)
Key Features
✅ Memory Efficient: Clears elements immediately after processing
✅ Streaming: Processes element-by-element
✅ JSON Compatible: Converts XML to dictionary format
✅ Filtering & Transform: Optional data manipulation
✅ Error Recovery: Handles malformed XML
✅ Batch Operations: Efficient database/file writing
✅ Garbage Collection: Periodic cleanup for stability
This approach handles gigabyte-scale XML files with minimal RAM!