Skip to main content
This article shows how to use XmlSerializer to turn XML into .NET objects, and what the serializer does when the XML doesn’t line up with the type. The API mirrors JsonSerializer.Deserialize in System.Text.Json: you name the target type as the type argument and pass the XML and, optionally, an XmlSerializerOptions instance.

Deserialize from a string

Call XmlSerializer.Deserialize<TValue> with the XML text.
Program.cs
PurchaseOrder.cs
The code produces the following output:
Notice the following:
  • The XML declaration, the indentation, and the line ends are all accepted. White space between elements isn’t part of any value.
  • The return type is nullable. The result is null when the document element is marked xsi:nil="true".
  • The name of the document element must be the name the type serializes as, here PurchaseOrder. Otherwise the serializer throws an XmlException. See Handle invalid XML.
View the complete sample on GitHub

Deserialize from UTF-8

XML read from a file or the network arrives as UTF-8 bytes. Pass the bytes directly. The reader works on UTF-8, so a string would be converted back to UTF-8 before it is parsed.

A span of bytes

The following example uses a u8 literal. A byte[] or a ReadOnlyMemory<byte>.Span works the same way, and an overload for ReadOnlySequence<byte> takes data that arrives in several segments.
Program.cs
The code produces the following output:

A stream

Pass a Stream. The serializer reads the stream to its end and doesn’t close it.
Program.cs
The code produces the following output:
To read a stream or a PipeReader without blocking, use DeserializeAsync. To receive the items of a large document one at a time, use DeserializeAsyncEnumerable. Both are covered in Streaming.
When the XML comes from a source you don’t control, set MaxDocumentByteCount and the other limits on the options. See Security.

Deserialize part of a document

You don’t have to map the whole document to a type. Read or parse the document yourself and hand the serializer only the elements you want as objects.

From a Utf8XmlReader

Move a Utf8XmlReader to a start tag and pass it by reference. The serializer reads that one element and leaves the reader on its end tag, so the loop continues with whatever follows.
Program.cs
The code produces the following output:

From a parsed document

Pass an XmlElement from an XmlDocument. Overloads also take the whole XmlDocument, which deserializes its root element, and a mutable XmlNode.
Program.cs
The code produces the following output:
In both cases the element you hand over is treated as a document element, so its name must be the name the type serializes as. An element called BillTo can’t be deserialized as an InvoiceCustomer this way, even though its content fits.

Deserialize a type known at run time

When the target type isn’t known at compile time, pass a Type. The method returns object.
Program.cs
The code produces the following output:

Missing, unknown, and out-of-order elements

Real documents rarely match a type exactly. By default the serializer is tolerant:
  • Elements may appear in any order.
  • A member with no element in the XML keeps the value the type gave it.
  • An element or attribute that no member maps to is skipped.
Program.cs
The code produces the following output:
Placed and Total aren’t in the XML, so they have their default values. The priority attribute and the Warehouse element are ignored. To make a missing member an error, mark it as required. To make an unknown element or attribute an error, set UnmappedMemberHandling:
Program.cs
The code produces the following output:
Both are covered in Require properties.

Match names without regard to case

Element and attribute names are matched to members with case, as XML names are case-sensitive. Set PropertyNameCaseInsensitive to match them without it.
Program.cs
The code produces the following output:
With the default options, id and CUSTOMER match no member and are skipped like any other unknown element. The comparison ignores the case of ASCII letters only: a name that holds any other character matches only when it is exactly the same. The option also applies to the name of the document element.

Handle invalid XML

The serializer throws an XmlException when the document element has the wrong name, when the XML isn’t well formed, and when a value can’t be converted to the member’s type.
Program.cs
The code produces the following output:
A document that isn’t well formed is never partly accepted: the serializer reads to the end of the document, so content after the document element is checked too.

Find where the error is

The exception says where in the document the error was. Path names each element from the document element down to the error, and LineNumber and LinePosition give the place in the text.
Program.cs
The code produces the following output:
View the complete sample on GitHub A path reads like this:
  • An entry of a dictionary is the element named for its key.
  • An item whose type is a derived type has the name its element has in the document.
  • The message ends with the path and, when it’s known, the line and the byte position in the line, in the form System.Text.Json uses.
  • An exception that a converter of yours throws gets a path too, and its message is left as you wrote it. A path you give to the XmlException constructor is left as it is.
  • When an object is written, the path is made of the elements the writer has open, with no positions: /Invoice/Lines. A value that is written as one whole element ends the path at the element that holds it.
  • Path is set by XmlSerializer. An XmlException from Utf8XmlReader, XmlDocument or XmlNode used on its own has no path.

Deserialization behavior

Unless you change it with options or attributes, XmlSerializer behaves as follows:
  • Names are matched with case. A member that is mapped to a namespace is matched by the namespace URI, never by the prefix. See Namespaces.
  • A member is set when it has a setter, including an init setter, or when it is a parameter of the constructor the serializer uses. See Immutable types.
  • A property with no setter is left alone, even when the XML has an element for it. To add to the collection, dictionary, or object it holds, use XmlObjectCreationHandling.Populate. See Serialize collections.
  • When an element appears twice for a member that isn’t a collection, the last one wins. Set AllowDuplicateProperties to false to throw instead.
  • An empty element, such as <Customer/>, is the empty string for a string member. Only xsi:nil="true" reads as null. See Handle null values.
  • White space inside a text value is kept. Character references, entity references such as &amp;, and CDATA sections are decoded.
  • Comments are skipped. A document type declaration (DTD) is rejected. See Security.

See also

Serialize

Write .NET objects as XML to each kind of destination.

Require properties

Reject XML that lacks a member or holds one the type doesn’t have.

Immutable types

Deserialize records, constructors with parameters, and structs.

Use Utf8XmlReader

Read XML token by token when you don’t want objects.