Recipe 12.6 · C#
Streaming Huge XML and JSON Files
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.
// Not to copy: the whole file in memory, then the whole list again
var doc = XDocument.Load(path);
var transactions = doc.Descendants("Transaction")
.Select(Map)
.ToList();
foreach (var 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>.
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace ImproveCode.Serialization;
public static class StreamingReaders
{
public static async IAsyncEnumerable<XElement> ReadElementsAsync(
string path,
string elementName,
[EnumeratorCancellation] CancellationToken ct = default)
{
var settings = new XmlReaderSettings
{
Async = true,
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
IgnoreWhitespace = true,
IgnoreComments = true,
};
using XmlReader reader = XmlReader.Create(path, settings);
await reader.MoveToContentAsync();
while (!reader.EOF)
{
ct.ThrowIfCancellationRequested();
if (reader.NodeType == XmlNodeType.Element
&& reader.LocalName == elementName)
{
// ReadFromAsync leaves the reader on the next node,
// so do not call ReadAsync again on this path.
var node = await XNode.ReadFromAsync(reader, ct);
yield return (XElement)node;
}
else
{
await reader.ReadAsync();
}
}
}
public static async IAsyncEnumerable<T> ReadJsonArrayAsync<T>(
string path,
JsonSerializerOptions options,
[EnumeratorCancellation] CancellationToken ct = default)
{
await using var stream = new FileStream(
path, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 64 * 1024, useAsync: true);
await foreach (T? item in JsonSerializer
.DeserializeAsyncEnumerable<T>(stream, options, ct))
{
if (item is not null)
{
yield return item;
}
}
}
}
Usage, processing in batches of 1,000:
var batch = new List<Transaction>(1000);
await foreach (XElement e in StreamingReaders
.ReadElementsAsync(path, "Transaction", ct))
{
batch.Add(Transaction.FromXml(e));
if (batch.Count == 1000)
{
await repository.SaveBatchAsync(batch, ct);
batch.Clear();
}
}
if (batch.Count > 0)
{
await repository.SaveBatchAsync(batch, ct);
}
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.
DeserializeAsyncEnumerablehandles a root-level array. For{ "transactions": [ ... ] }, either ask the producer for JSON Lines (one object per line, read withStreamReader.ReadLineAsyncandJsonSerializer.Deserialize) or, on .NET 9, use thetopLevelValuesoverload for newline-delimited documents. A hand-writtenUtf8JsonReaderloop is the last resort. - Typed records from XML. If each element maps to an
XmlSerializerclass, callserializer.Deserialize(reader.ReadSubtree())instead ofXNode.ReadFromAsync, with the serializer cached as in Recipe 12.3. - Compressed feeds. Wrap the file stream in
GZipStreamand pass that toXmlReader.Createor 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.