XmlSerializer with a Stream, a PipeReader, or a PipeWriter, and how to move a sequence of values through one of them without holding the whole sequence in memory. You need it for HTTP bodies, files, sockets, and feeds that are too large or too slow to treat as one string.
The method names are the ones System.Text.Json uses: SerializeAsync, DeserializeAsync, SerializeAsyncEnumerable, and DeserializeAsyncEnumerable. The examples use this type:
SensorReading.cs
Serialize one document to a stream
SerializeAsync writes one document to a stream, and DeserializeAsync reads one document from a stream. Neither blocks a thread while the stream is busy.
Program.cs
These two methods are asynchronous, but they are not incremental.
SerializeAsync builds the document in a pooled buffer and then writes it to the stream with one asynchronous write. DeserializeAsync reads the stream to its end into a pooled buffer and then deserializes. Memory use grows with the size of the document. XmlSerializerOptions.MaxDocumentByteCount stops a read as soon as the limit is exceeded. To process a large document piece by piece, use the sequence methods in the next section.Serialize(Stream, ...) and Deserialize<T>(Stream, ...), are the blocking equivalents.
View the complete sample on GitHub
Write and read a sequence
SerializeAsyncEnumerable takes an IAsyncEnumerable<T> and writes each value as it arrives. DeserializeAsyncEnumerable returns an IAsyncEnumerable<T> that produces each value as soon as the stream has delivered all of its bytes. By default, the values are the children of one document element.
The examples use this method as the source of values:
Program.cs
Program.cs
- The document element is named
ArrayOffollowed by the root name ofTwith a capital first letter, which is the name aList<T>or aT[]has at the root. The whole name then goes through the element naming policy, so underCamelCaseit starts witharrayOf. Each value is written under the root name ofT. You can’t change the wrapper’s name. The wrapper is in the same namespace as the values, soXmlSerializerOptions.DefaultNamespaceis declared once, on the wrapper. - With a
ReferenceHandler, the values of the document share one set of references: an object that two values hold is written once, and it is read back as one object. WithtopLevelValueseach value is a document of its own, with references of its own. DeserializeAsyncEnumerablereads every child of the document element as aT. It doesn’t check the name of the document element or the names of its children, so it can read a sequence that another system wrapped in an element of its own, such as<Feed>.Deserialize<List<T>>andDeserialize<T[]>read this document, andDeserializeAsyncEnumerablereads whatSerializewrites for aList<T>or aT[]: the three write the same thing.- An empty sequence writes an empty document element, and reading it produces no values.
Write each value as its own document
PasstopLevelValues: true to write every value as a complete document, one after another in the same stream. This is the counterpart of the JSON Lines form that System.Text.Json reads and writes with the parameter of the same name. It suits a log or a feed that is appended to and never closed.
Program.cs
View the complete sample on GitHub
Use pipes
System.IO.Pipelines is the I/O model that ASP.NET Core uses for request and response bodies. The serializer accepts both ends of a pipe:
The pipe overloads of the sequence methods that take options require the
topLevelValues argument. In the next example, one task writes a sequence to a pipe while the calling method reads it from the other end.
Program.cs
Program.cs
Cancel an operation
Every asynchronous method takes aCancellationToken. The token is passed to the stream’s read and write calls, and the sequence methods also check it between values. A canceled operation throws OperationCanceledException.
Program.cs
Memory behavior
- Reading a sequence. After each read from the stream,
DeserializeAsyncEnumerablereturns every value that is now complete. A value is returned only once all of it has been read; your loop never sees a value that is still being filled. The buffer starts atXmlSerializerOptions.DefaultBufferSize(0, which means 16,384 bytes) and comes from the shared array pool. It goes back when the enumeration ends, so dispose the enumerator if you stop early.await foreachdoes that for you. - Values that span reads. In the wrapped form, an object whose members are built-in simple values, other such objects, or collections of either is read a piece at a time: what it has read so far is kept between reads, the bytes it has used are released, and nothing is read twice. So the buffer doesn’t have to hold a whole value, and it grows only when it fills with bytes that can’t be used yet. Any other value is read once all of it is in the buffer, which then doubles as often as the value needs. That applies with
topLevelValues: true, with aReferenceHandler, to a value that isn’t an object, and to an object with polymorphism, text or mixed content, extension data, a member that is populated, or a member whose type is read some other way, such as a dictionary or a type with a converter of your own. - Writing a sequence. Each value is written into the writer’s buffer and passed to the stream between values, never in the middle of one, unless a single value is larger than the buffer.
- Malformed input. A value that can’t be read throws
XmlExceptionwhen the reader reaches it. The values before it have already been returned to your loop. - Reference handling. The sequence methods apply
XmlReferenceHandler. In the wrapped form the values share one set of references, so a value may hold arefto an object that an earlier value defined. Read the values in order and keep them if you rely on that. WithtopLevelValues, each value has its own references.
Performance
The library’s benchmarks move a sequence of 1,000 values through aMemoryStream with these methods and with the same methods in System.Text.Json. System.Xml has no streaming call for a sequence, so it is measured reading and writing an array whole. See Benchmarks for the method and the results.
Use source generation
The stream overloads of every method on this page, and thePipeReader overloads, also come in a form that takes an XmlTypeInfo<T> from a generated context instead of XmlSerializerOptions. The PipeReader form of DeserializeAsyncEnumerable that takes an XmlTypeInfo<T> reads the wrapped form only; to read top-level values from a pipe with generated metadata, pass pipeReader.AsStream() to the Stream overload. Use that form in trimmed and Native AOT applications. The two PipeWriter overloads take options only. To write to a pipe with generated metadata, pass the PipeWriter to Serialize(IBufferWriter<byte>, value, xmlTypeInfo) and flush it yourself. See Source generation.
See also
Serialize
Write objects to strings, byte arrays, and writers.
Deserialize
Read objects from strings, UTF-8 bytes, and readers.
Collections
Serialize lists and arrays that fit in memory.
Use Utf8XmlReader
Read a large document token by token.