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.
var serializer = new XmlSerializer(typeof(Person)); serializer.Serialize(writer, new Person { Name = "Ada" }); Person? back = (Person?)serializer.Deserialize(reader);
Try it
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.
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
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 arenullare skipped (or written asxsi:nilwhenIsNullable = trueon the element). - No dictionaries, no cycles.
Dictionary<TKey, TValue>is not supported (use a list of key/value classes), and circular references throw.privatedata is ignored. - Unknown input is ignored. Extra elements and attributes are skipped silently; subscribe to
UnknownElementorUnknownAttributeto notice them. - Reuse the serializer. Creating an
XmlSerializerfor a type generates and compiles serialization code once per process. Cache the instance in astatic readonlyfield. The constructors that takeXmlAttributeOverridesare not cached by the runtime, so keep those instances too to avoid a memory leak. - Security. Do not point an
XmlReaderwith DTD processing enabled at untrusted XML. The defaultXmlReaderSettingsprohibit DTDs; keep it that way (DtdProcessing.Prohibit). - Trimming and AOT.
XmlSerializerrelies on runtime code generation and is not trim- or AOT-friendly. PreferSystem.Text.Jsonwith source generation in those environments. - Alternatives.
DataContractSerializerhandles private members and dictionaries, but has a more rigid XML shape.XDocumentis easier when the format is irregular.