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
CallXmlSerializer.Deserialize<TValue> with the XML text.
Program.cs
PurchaseOrder.cs
- 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
nullwhen the document element is markedxsi:nil="true". - The name of the document element must be the name the type serializes as, here
PurchaseOrder. Otherwise the serializer throws anXmlException. See Handle invalid XML.
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 astring would be converted back to UTF-8 before it is parsed.
A span of bytes
The following example uses au8 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
A stream
Pass aStream. The serializer reads the stream to its end and doesn’t close it.
Program.cs
PipeReader without blocking, use DeserializeAsync. To receive the items of a large document one at a time, use DeserializeAsyncEnumerable. Both are covered in Streaming.
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 aUtf8XmlReader 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
From a parsed document
Pass anXmlElement from an XmlDocument. Overloads also take the whole XmlDocument, which deserializes its root element, and a mutable XmlNode.
Program.cs
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 aType. The method returns object.
Program.cs
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
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
Match names without regard to case
Element and attribute names are matched to members with case, as XML names are case-sensitive. SetPropertyNameCaseInsensitive to match them without it.
Program.cs
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 anXmlException 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
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
- 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.Jsonuses. - 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
XmlExceptionconstructor 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. Pathis set byXmlSerializer. AnXmlExceptionfromUtf8XmlReader,XmlDocumentorXmlNodeused 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
initsetter, 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
AllowDuplicatePropertiestofalseto throw instead. - An empty element, such as
<Customer/>, is the empty string for astringmember. Onlyxsi:nil="true"reads asnull. See Handle null values. - White space inside a text value is kept. Character references, entity references such as
&, 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.