Generic XML Serialization in C# with XmlSerializer

XmlSerializer turns the public properties and fields of an object into XML and rebuilds the object from that XML later. It is the right tool when you have to produce or consume an XML format defined by someone else, or when you maintain a config or data file that is already XML. The generic helper below wraps the boilerplate so a round trip takes two lines.

Usage

var article = new Article
{
    Name = "C# Examples",
    Url = "https://csharpexamples.com",
    Tags = ["csharp", "xml"],
    InternalNote = "This value won't be serialized"
};

string xml = GenericXmlSerializer<Article>.Serialize(article);
Console.WriteLine(xml);

Article copy = GenericXmlSerializer<Article>.Deserialize(xml);
Console.WriteLine(copy.Tags.Count); // 2

The first WriteLine prints:

<Article Name="C# Examples" Url="https://csharpexamples.com">
  <Tags>
    <Tag>csharp</Tag>
    <Tag>xml</Tag>
  </Tags>
</Article>

The class being serialized:

using System.Xml.Serialization;

public class Article
{
    [XmlAttribute]
    public string Name { get; set; } = "";

    [XmlAttribute]
    public string Url { get; set; } = "";

    [XmlArrayItem("Tag")]
    public List<string> Tags { get; set; } = [];

    [XmlIgnore]
    public string? InternalNote { get; set; }
}

Without attributes, every public property becomes a child element named after the property. [XmlAttribute] writes it as an attribute instead, [XmlArrayItem] names the items of a collection, and [XmlIgnore] leaves a property out. [XmlElement("name")] and [XmlRoot("name")] rename elements when the target format uses different names from your C# code.

The helper

using System.Xml;
using System.Xml.Serialization;

public static class GenericXmlSerializer<T>
{
    // One serializer per T. The constructor is expensive, so build it once.
    private static readonly XmlSerializer Serializer = new(typeof(T));

    // Suppresses the xmlns:xsi and xmlns:xsd declarations on the root element.
    private static readonly XmlSerializerNamespaces NoNamespaces =
        new(new[] { XmlQualifiedName.Empty });

    public static string Serialize(T value)
    {
        var settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true };

        using var stringWriter = new StringWriter();
        using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
        {
            Serializer.Serialize(xmlWriter, value, NoNamespaces);
        }
        return stringWriter.ToString();
    }

    public static T Deserialize(string xml)
    {
        using var stringReader = new StringReader(xml);
        using var xmlReader = XmlReader.Create(stringReader);
        return (T)Serializer.Deserialize(xmlReader)!;
    }

    public static void SaveToFile(T value, string path)
    {
        using FileStream stream = File.Create(path);
        Serializer.Serialize(stream, value, NoNamespaces);
    }

    public static T LoadFromFile(string path)
    {
        using FileStream stream = File.OpenRead(path);
        using var xmlReader = XmlReader.Create(stream);
        return (T)Serializer.Deserialize(xmlReader)!;
    }
}

A static generic class gives each T its own static fields, so GenericXmlSerializer<Article> and GenericXmlSerializer<Order> each hold one cached serializer with no dictionary or locking. XmlSerializer is thread safe for Serialize and Deserialize, so sharing it is fine.

Rules your classes must follow

  • The class must be public and have a public parameterless constructor. Positional records such as record Article(string Name, string Url) fail for that reason.
  • Only public read/write properties and public fields are serialized. Get-only properties are skipped, except collections, which the serializer fills through the getter.
  • Dictionary<TKey, TValue> and other IDictionary types are not supported; the XmlSerializer constructor throws. Use a list of key/value items instead.
  • Derived types need [XmlInclude(typeof(Derived))] on the base class, otherwise serializing an instance of the derived type throws.

Traps

Encoding declarations. With a StringWriter and the XML declaration left on, the output starts with encoding="utf-16", because .NET strings are UTF-16. Save that string to a UTF-8 file and some parsers will refuse it. The helper omits the declaration for strings and serializes straight to a FileStream for files, where it writes UTF-8, the encoding every XML parser assumes when none is declared.

Silent failures. The original version of this helper called CanDeserialize and returned default(T) when the root element did not match. That hides bugs. Let Deserialize throw: it raises an InvalidOperationException whose InnerException points at the line and position of the problem.

Memory leaks with other constructors. Only new XmlSerializer(Type) and new XmlSerializer(Type, string) reuse their generated code. Overloads that take an XmlRootAttribute, XmlAttributeOverrides or extra types generate a new assembly on every call, and those are never unloaded. If you need them, create the serializer once and keep it in a static field, as above.

Untrusted input. XmlReader.Create prohibits DTDs by default, which blocks entity expansion attacks, and XmlSerializer only instantiates the types it was built for. That makes it a reasonable choice for data you did not produce, unlike BinaryFormatter, which was removed in .NET 9.

If you are designing a new format rather than matching an existing one, consider System.Text.Json. It is faster, works with records and immutable types, and supports dictionaries.

Related examples

Leave a Comment