XmlSerializer reads and writes without a custom converter. For each type it gives the text that is written and the text that is accepted, so you can tell whether a document from another system will deserialize. The rules follow XML Schema Part 2: Datatypes, and they don’t depend on the current culture.
The typed getters on Utf8XmlReader and XmlElement, such as GetInt32 and GetDateTime, parse values with the same code as the serializer. A value that one of them accepts is accepted by all three.
Built-in types at a glance
The following sample serializes one value of each built-in scalar type as the document element.Print writes the C# name of the type and the result of XmlSerializer.Serialize:
int, boolean, string, dateTime, base64Binary for byte[], and so on. These are the names System.Xml.Serialization writes. A type XML Schema has no name for is named the same way (guid, dateOnly, dateTimeOffset) or by its .NET name (TimeSpan, an enumeration). A nullable value type has the name of the underlying type. A property uses its own name instead. The text inside the element is the same in both cases, and it is the same when the property is written as an XML attribute.
Numbers and Boolean values
Things to notice:
- Integers don’t accept group separators (
1,000), hexadecimal (0x1F), a fraction (1.0), or an exponent. - A value outside the range of the type is rejected. It never wraps.
Infinityand+INFare rejected. Only the three XSD names are accepted. Accepting them in any letter case is an extension to XML Schema.- A finite-looking number that is too large for the type, such as
1e400for adouble, reads as infinity. - To reject
NaN,INF, and-INFin both directions, setXmlSerializerOptions.NumberHandlingtoXmlNumberHandling.Strict. Writing a value that isn’t finite then throws anXmlExceptionwith the messageNamed floating-point literals are not allowed when NumberHandling is Strict.
Dates, times, and durations
The kind of a
DateTime that is read depends on the time zone in the text:
A
DateTimeOffset read from text that has no time zone takes the offset of the local time zone at that date and time.
Rules that hold for all date and time types:
- Every field has a fixed width.
2026-1-2T03:04:05and14:30are rejected. TheTis uppercase, and a space isn’t accepted in its place. - A fraction of a second is written with up to seven digits and no trailing zeros. On read, digits after the seventh are dropped.
24:00:00is accepted and means the first instant of the next day. For aTimeOnlyit reads as00:00:00.- Seconds are
00to59. A time zone isZor an offset of up to 14 hours. - The year has exactly four digits,
0001to9999, because that is the range of the .NET types. XML Schema allows longer and negative years. - A duration that names years or months, such as
P1YorP1M, is rejected. A year and a month have no fixed length, so they can’t be stored in aTimeSpan. The .NET format01:02:03is also rejected.
Text, binary data, and identifiers
For every type except
string, leading and trailing spaces, tabs, and line ends are removed before the value is parsed. XML Schema calls this the collapse whitespace rule.
Read forms other than the one that is written
The following sample deserializes values that are legal but aren’t written the way the serializer writes them. The last value is rejected.XmlException with one of these messages:
An empty element is not a number, a Boolean value, or a date.
<int/> is rejected for both int and int?.
Enums
An enum is written as the name of its member. A[Flags] enum is written as the names of the members that are set, separated by spaces. Set XmlSerializerOptions.EnumHandling to XmlEnumHandling.Integer to write the number instead.
Models
Names are matched in any case, so
shipped reads as Shipped; an exact match is tried first, and a name given with [XmlPropertyName] must match exactly. A comma isn’t a separator: Gift, Insured, the form Enum.ToString produces, is rejected. For an enum without [Flags], a number that isn’t a declared member, such as 7 for OrderStatus, is rejected.
System.Text.Json writes enums as numbers by default. XmlEssentials writes names by default.
Nullable value types
Nullable<T> is supported for every value type in the tables above and for every enum. A value is written exactly as T is. null is written as an empty element with xsi:nil="true" when it is the document element or an item of a collection, as the last line of the first sample shows. For a property, what is written depends on your options. See Handle null values and xsi:nil.
Reading an element with xsi:nil="true" into a type that can’t be null, such as int, throws an XmlException: The element is nil but type 'System.Int32' is not nillable.
Collections and dictionaries
A collection is written as one child element for each item. A dictionary is written as one child element for each entry.Key element followed by a Value element. The key Key itself is written in the pair form.
This page shows the shape only. To name the items, wrap or unwrap a collection property, and populate read-only collection properties, see Serialize collections.
Every collection and dictionary that can be written can be read. The following table shows what a member of each declared type holds after it is read.
Your own collection type is supported when the serializer can create it. It needs one of the following:
- A public parameterless constructor, and either
ICollection<T>or a publicAddmethod that takes one item. - A public constructor that takes
IEnumerable<T>orIList<T>. - For a dictionary, a public parameterless constructor and
IDictionary<TKey, TValue>, or a public constructor that takesIDictionary<TKey, TValue>.
NotSupportedException with a message that names the type and what it needs.
Items are read in document order. A stack is written from its top down, and it is read back with the same top, so a stack survives a round trip unchanged.
Items, keys, and values can be any supported type, including other collections and your own classes. A null item is written with xsi:nil="true". A null dictionary value is written the same way and reads back as null. See Handle null values.
Classes, structs, and records
A concrete class or struct that isn’t in the tables above is mapped as an object: each public property becomes a child element. See Serialize .NET objects as XML, Use immutable types and records, and Polymorphism.XML values, object, and anonymous types
A value that is XML already is written as the XML it is.XmlElement, XmlDocument, XmlNode, and XmlElementNode are such types.
- As the value you serialize, it is the document.
XmlSerializer.Serialize(element)writes the element under its own name, andDeserialize<XmlElement>reads any document element. - As a member, it is the one element inside the member’s element. A member named
Payloadthat holds<order id="7"/>is written as<Payload><order id="7"/></Payload>. - Only an element can be the value. Serializing a text node throws
NotSupportedException. - An
XmlDocumentis written as its document element. Its XML declaration and any comment outside the document element aren’t written. - An element, document, or node that the serializer reads holds no pooled memory, so you don’t have to dispose it.
object is written as the type it has. XmlSerializer.Serialize<object>(42) writes <int>42</int>, and a member declared as object writes the value inside the member’s element. A document doesn’t record which type wrote an element, so a value declared as object is read as an XmlElement. Read it as the type you expect with XmlSerializer.Deserialize<T>(element). To read an XmlNode that can be changed instead, set XmlSerializerOptions.UnknownTypeHandling to XmlUnknownTypeHandling.XmlNode.
The element you get is the member’s own element: <Any><b>1</b></Any> is read as an element named Any. When that value is written again, its attributes and children go inside the member’s element, so the document comes back as it was read. The same holds for a list item and a dictionary value. The member names the element, so an XmlElement you built under another name is written under the member’s name.
An anonymous type is written under the element name AnonymousType, and each property becomes a child element. It can be read back through its constructor when you have a value of the type to infer it from.
Types that aren’t supported
The serializer throwsNotSupportedException for a type that it has no converter for. The message names the type.
A
ValueTuple is written as an empty element unless IncludeFields is true, because its items are fields. Tuple<T1, T2> and KeyValuePair<TKey, TValue> are written with their properties and read back through their constructors.XmlSerializerOptions.Converters is used before the built-in one. See Write custom converters.
Native AOT and trimming
The converters for the scalar types on this page, and for the nullable forms of the value types, are created without reflection. Enums, collections, dictionaries, and objects need metadata that is either found by reflection at run time or generated at compile time. For a trimmed or Native AOT application, list those types on anXmlSerializerContext. See Use source generation and Native AOT.
See also
Serialize collections
Name items, wrap and unwrap lists, and map dictionaries.
Handle null values and xsi:nil
Choose how null is written and read.
Write custom converters
Support a type that isn’t built in, or change how one is written.
XML conformance
The XML rules the reader and writer apply to every value.