Recipe 12.3 · C#
XmlSerializer Without the Leaks
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
A trading partner sends invoices as XML, and you would rather work with a class than with nodes.
XmlSerializer does that job well, but it has a few traps: one constructor overload leaks memory,
StringWriter produces a UTF-16 declaration your partner rejects, the output carries namespace
declarations nobody asked for, and default reader settings are more trusting than they should be.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: leaks an assembly per call, UTF-16 header, xsi/xsd noise
public static string ToXml<T>(T value)
{
var serializer = new XmlSerializer(
typeof(T), new XmlRootAttribute("Invoice"));
using (var writer = new StringWriter())
{
serializer.Serialize(writer, value);
return writer.ToString();
}
}
public static T FromXml<T>(string xml)
{
var doc = new XmlDocument();
doc.LoadXml(xml); // DTDs on older frameworks
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new XmlNodeReader(doc));
}
XmlSerializer generates and loads a dynamic assembly for each type it handles. The
XmlSerializer(Type) and XmlSerializer(Type, string) constructors cache that assembly. Every
other overload, including the one that takes an XmlRootAttribute, generates a fresh assembly on
every call, and assemblies are never unloaded. I once traced an app pool that recycled every few
hours to exactly this line in a helper class.
The improved recipe
Cache serializers yourself, keyed by type and root name. Write UTF-8 without a byte-order mark,
suppress the default namespaces, and read through an XmlReader that refuses DTDs.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ImproveCode.Serialization;
public static class XmlHelper
{
private static readonly
ConcurrentDictionary<(Type, string?), XmlSerializer> Cache = new();
private static readonly XmlReaderSettings ReaderSettings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
IgnoreComments = true,
};
private static readonly XmlWriterSettings WriterSettings = new()
{
Encoding = new UTF8Encoding(false),
Indent = true,
};
private static readonly XmlSerializerNamespaces NoNamespaces =
CreateEmptyNamespaces();
public static void Serialize<T>(
T value, Stream stream, string? rootName = null)
{
using var writer = XmlWriter.Create(stream, WriterSettings);
GetSerializer(typeof(T), rootName)
.Serialize(writer, value, NoNamespaces);
}
public static string Serialize<T>(T value, string? rootName = null)
{
using var stream = new MemoryStream();
Serialize(value, stream, rootName);
return Encoding.UTF8.GetString(stream.ToArray());
}
public static T Deserialize<T>(Stream stream, string? rootName = null)
{
using var reader = XmlReader.Create(stream, ReaderSettings);
return Read<T>(reader, rootName);
}
public static T Deserialize<T>(string xml, string? rootName = null)
{
using var text = new StringReader(xml);
using var reader = XmlReader.Create(text, ReaderSettings);
return Read<T>(reader, rootName);
}
private static T Read<T>(XmlReader reader, string? rootName)
{
object? result = GetSerializer(typeof(T), rootName)
.Deserialize(reader);
return result is T typed
? typed
: throw new InvalidDataException(
$"XML did not contain a {typeof(T).Name}.");
}
private static XmlSerializer GetSerializer(
Type type, string? rootName) =>
Cache.GetOrAdd((type, rootName), key => key.Item2 is null
? new XmlSerializer(key.Item1)
: new XmlSerializer(
key.Item1, new XmlRootAttribute(key.Item2)));
private static XmlSerializerNamespaces CreateEmptyNamespaces()
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
return namespaces;
}
}
A class shaped for XmlSerializer looks like this:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace ImproveCode.Serialization;
[XmlRoot("Invoice")]
public sealed class InvoiceXml
{
[XmlAttribute("number")]
public string Number { get; set; } = "";
[XmlElement("IssuedOn", DataType = "date")]
public DateTime IssuedOn { get; set; }
public string Customer { get; set; } = "";
[XmlArray("Lines")]
[XmlArrayItem("Line")]
public List<InvoiceLineXml> Lines { get; set; } = [];
}
public sealed class InvoiceLineXml
{
[XmlAttribute("sku")]
public string Sku { get; set; } = "";
[XmlAttribute("qty")]
public int Quantity { get; set; }
[XmlText]
public decimal Amount { get; set; }
}
How it works
The cache key is a tuple of the type and the optional root name, so each combination builds its
serializer exactly once per process. ConcurrentDictionary.GetOrAdd may run the factory twice
under a race, which costs one extra serializer at most, never one per call.
Writing through an XmlWriter over a Stream with new UTF8Encoding(false) gives a declaration
of encoding="utf-8" and no byte-order mark. Writing to a StringWriter would declare UTF-16,
because .NET strings are UTF-16, and partners who validate the header reject it. The empty
XmlSerializerNamespaces removes the xmlns:xsi and xmlns:xsd declarations the serializer adds
by default.
On the reading side, DtdProcessing.Prohibit and a null XmlResolver stop entity-expansion
attacks and external entity references (XXE) from files you did not write. Modern .NET is safe by
default here, but stating the settings documents the intent and keeps the code safe if it is ever
copied back to an older framework.
DataType = "date" writes 2025-03-31 instead of a full timestamp, which is what most invoice
schemas expect. [XmlText] puts the amount in the element body, so a line reads
<Line sku="A-100" qty="2">19.98</Line>.
Variations and pitfalls
- XmlSerializer needs a public parameterless constructor and public settable properties.
Records with positional parameters and
init-only properties don't work. Keep XML-shaped classes separate from your domain types and map between them. DateTimeOffsetis not supported. It serializes as an empty element. UseDateTimewithDataType = "dateTime", or a string property that you parse.- Optional value types. For an element that may be absent, add a
bool QuantitySpecifiedproperty next toQuantity. The serializer reads and writes it by convention. - Interfaces and dictionaries cannot be serialized. Use concrete lists, or a list of key-value classes.
- Validating against a schema. If the partner provides an XSD, add it to
XmlReaderSettings.Schemas, setValidationType = ValidationType.Schema, and handleValidationEventHandler. Reject the file before you deserialize it.
On .NET Framework
The helper works unchanged on .NET Framework 4.7.2 and later once you replace the collection
expressions with new List<...>(). On versions before 4.5.2, XmlDocument and XmlTextReader
resolve external entities by default, so the explicit reader settings are not optional there.