Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

XML serialization with XmlSerializer

Reference for XmlSerializer in C#: Serialize and Deserialize objects to XML, XmlRoot, XmlAttribute, XmlElement, XmlArray, XmlIgnore and common pitfalls.

System.Xml.Serialization.XmlSerializer converts objects to XML and back. You create a serializer for a type, then call Serialize(writer, obj) to write XML and Deserialize(reader) to read it. The shape of the XML is controlled by attributes on the class and its members: [XmlRoot], [XmlElement], [XmlAttribute], [XmlArray], [XmlArrayItem], [XmlText] and [XmlIgnore].

XmlSerializer has strict rules: the type must be public and have a public parameterless constructor, and only public read/write properties and public fields are serialized. It is the right tool for fixed XML formats and older configuration files; for new data exchange most code uses JSON instead, and for flexible documents XDocument is easier.

C#
var serializer = new XmlSerializer(typeof(Person));
serializer.Serialize(writer, new Person { Name = "Ada" });
Person? back = (Person?)serializer.Deserialize(reader);

Try it

C# Objects to XML and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Reading existing XML and handling errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public XmlSerializer(Type type);
public XmlSerializer(Type type, XmlRootAttribute? root);
public XmlSerializer(Type type, Type[]? extraTypes);

public void Serialize(TextWriter textWriter, object? o);
public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces);
public void Serialize(Stream stream, object? o);
public object? Deserialize(TextReader textReader);
public object? Deserialize(XmlReader xmlReader);
public object? Deserialize(Stream stream);
public bool CanDeserialize(XmlReader xmlReader);
Name Description
type The root type. Add derived types through extraTypes or [XmlInclude].
root Overrides the root element name or namespace.
namespaces Controls namespace prefixes. An empty prefix with an empty namespace removes the default xsi and xsd declarations.
Attributes [XmlRoot] names the root, [XmlElement] and [XmlAttribute] name members, [XmlArray]/[XmlArrayItem] name a wrapper and its items, [XmlText] maps to element text, [XmlIgnore] skips a member, [XmlInclude] registers derived types.

Returns: Deserialize returns object?, which you cast to the root type.

Errors: InvalidOperationException both when the type cannot be serialized (no parameterless constructor, interfaces, unsupported members) and when the XML is malformed or does not fit the type; the real reason is in InnerException.

Usage notes

  • Type rules. The type and its members must be public, the type needs a public parameterless constructor, and properties need public getters and setters. Read-only collection properties are allowed if initialized, because the serializer adds items to them.
  • Members are elements by default. Use [XmlAttribute] to write a value as an attribute. Only simple types can become attributes.
  • Collections. A List<T> property becomes a wrapper element with children named after the type unless you configure [XmlArray]/[XmlArrayItem], or use [XmlElement] to repeat the item element with no wrapper.
  • Optional values. A ShouldSerializeX() method or a [DefaultValue] attribute omits a member from the output. Nullable value types that are null are skipped (or written as xsi:nil when IsNullable = true on the element).
  • No dictionaries, no cycles. Dictionary<TKey, TValue> is not supported (use a list of key/value classes), and circular references throw. private data is ignored.
  • Unknown input is ignored. Extra elements and attributes are skipped silently; subscribe to UnknownElement or UnknownAttribute to notice them.
  • Reuse the serializer. Creating an XmlSerializer for a type generates and compiles serialization code once per process. Cache the instance in a static readonly field. The constructors that take XmlAttributeOverrides are not cached by the runtime, so keep those instances too to avoid a memory leak.
  • Security. Do not point an XmlReader with DTD processing enabled at untrusted XML. The default XmlReaderSettings prohibit DTDs; keep it that way (DtdProcessing.Prohibit).
  • Trimming and AOT. XmlSerializer relies on runtime code generation and is not trim- or AOT-friendly. Prefer System.Text.Json with source generation in those environments.
  • Alternatives. DataContractSerializer handles private members and dictionaries, but has a more rigid XML shape. XDocument is easier when the format is irregular.