XmlSerializer uses by default, how to add a wrapper and name the items, how dictionaries are mapped, and which collection types can be read back.
Repeated elements without a wrapper
By default, a collection member is written as one element per item, each named after the member. There is no wrapper element.Playlist.cs
Program.cs
This default differs from
System.Xml.Serialization.XmlSerializer, which wraps a collection in an element named after the member and names each item after its type. If you’re matching XML produced by that serializer, set DefaultCollectionMapping to XmlCollectionMapping.Wrapped to wrap every collection that has no mapping attribute, or add [XmlArray] to one member as shown in the next section. See Migrate from XmlSerializer.Name the repeated elements
The plural member name often reads badly on an item. To rename the repeated elements, rename the member with[XmlElement] or [XmlPropertyName].
NewsFeed.cs
Program.cs
A wrapper element with named items
Add[XmlArray] to put the items inside one element, and [XmlArrayItem] to name the items.
Album.cs
Program.cs
[XmlArray] with no name uses the member name for the wrapper. Without [XmlArrayItem], each item is named after its .NET type:
Scoreboard.cs
Program.cs
int or string, and the class name otherwise. These are the names System.Xml.Serialization writes. An element naming policy on the options applies to default wrapper and item names, and doesn’t change names you set in the attributes.
Wrap every collection
To wrap every collection without marking each member, setXmlSerializerOptions.DefaultCollectionMapping to XmlCollectionMapping.Wrapped. A collection member with no mapping attribute then gets a wrapper named after the member and items named for their type, as if it had [XmlArray].
Album.cs
Program.cs
- The setting applies to members with no mapping attribute. A member with
[XmlElement]stays unwrapped, and a member with[XmlArray]or[XmlArrayItem]keeps the names you gave it. - A dictionary is written the same way under either value: it always has an element of its own.
- Read the document with the options that wrote it. The setting decides where the serializer looks for the items.
XmlSerializerOptions.BclsetsWrapped, along with the other settings that matchSystem.Xml.Serialization.XmlSerializer. See Migrate from XmlSerializer.
Empty and null collections
The two shapes differ in what they can express. Without a wrapper there is no element to carry “empty” or “null”, so both write nothing. A wrapper can show the difference.Program.cs
When the XML has no element for a collection member, the serializer doesn’t touch the member. It keeps whatever the type’s initializer or constructor gave it.
Playlist.Tracks is initialized to an empty list, so an unwrapped empty list reads back as empty. If the property had no initializer, it would read back as null.
One option changes the null row for a wrapped collection:
- With an ignore condition of
WhenWritingNull,WhenWritingNullReference, orWhenWritingDefault, on the member or asDefaultIgnoreCondition, anullwrapped collection is left out.
null item inside a collection is written as an element marked xsi:nil="true" and reads back as null.
Dictionaries
A dictionary is always written inside an element named after the member. Each entry whose key is a string that is also a valid XML name becomes an element named by the key. Any other entry becomes aKey element followed by a Value element.
AppSettings.cs
Program.cs
Support email has a space, so it can’t be an element name and is written as a pair. All three entries read back.
The rules for the two forms are:
- The element form is used for a
stringkey made of ASCII letters, digits,.,-, and_that starts with a letter or_. - The pair form is used for every other string key, for the key
Keyitself (an element namedKeystarts a pair when reading), and for every key that isn’t a string, such as anintor aGuid. - A
nullvalue is written as an element markedxsi:nil="true", whatever the ignore condition, and reads back asnull. In the pair form the mark is on<Value>. - If the same key appears twice when reading, the last entry wins.
Dictionary key policy
DictionaryKeyPolicy converts string keys when writing. When it’s null, PropertyNamingPolicy is used.
Program.cs
PageSize went out and pageSize came back. Use a key policy only when the reader of the XML expects the converted names. The same applies to PropertyNamingPolicy, which changes dictionary keys too unless you set DictionaryKeyPolicy.
Collection types
Any type that implementsIEnumerable<T> can be written, apart from string and byte[]: a byte[] is one base64 value, not a list. Reading is narrower, because the serializer has to create the collection.
StockReport.cs
Program.cs
Every collection type that can be written can be read. A stack is written from its top down and is read back with the same top. A class of your own is read when it has a public parameterless constructor and either implements
ICollection<T> or has a public Add method, or when it has a public constructor that takes IEnumerable<T> or IList<T>. A class with none of these is written, and reading it throws NotSupportedException.
The complete list of supported types is in Supported types.
Populate a collection that already holds a value
By default a member is given a new value when it is read, and a property with no setter is not read at all. That isXmlObjectCreationHandling.Replace, and it is what System.Text.Json does. To keep the value a member already holds and add to it, use XmlObjectCreationHandling.Populate:
- The items of a collection and the entries of a dictionary are added to the instance the member holds. An entry whose key the dictionary already holds takes the value from the XML.
- The members of an object are set on the object the member holds. The members the XML leaves out keep their values.
- A member that holds
nullis given a new instance when it has a setter. - An element marked
xsi:nil="true"sets a member that has a setter tonull. For a member with no setter, the serializer throws anInvalidOperationException.
PreferredObjectCreationHandling leaves them as they are under Replace, and [XmlObjectCreationHandling(XmlObjectCreationHandling.Populate)] on such a member throws an InvalidOperationException the first time the type is used:
- An array, an immutable or frozen collection, a collection or dictionary that is a value type, and a collection declared as a read-only interface such as
IEnumerable<T>orIReadOnlyList<T>. - A collection or dictionary class with no public parameterless constructor, such as
ReadOnlyCollection<T>, and a collection class that doesn’t implementICollection<T>, other thanStack<T>andQueue<T>. - A member marked
[XmlIgnore(Condition = XmlIgnoreCondition.WhenReading)], which is never read. - A single value such as a
stringor a number. - A value that has a custom converter, and mixed content.
- A polymorphic type.
- A value type with no setter.
- A type that is created through a constructor with parameters populates none of its members. The attribute on such a type, or on one of its members, throws a
NotSupportedException. Populatecan’t be combined withReferenceHandler. A type with a member to populate throws anInvalidOperationException.
IList<T> or ICollection<T> is populated through the interface. If it holds an array or another read-only collection at run time, the serializer throws a NotSupportedException.
A source-generated context populates in the same way: it adds to collections and dictionaries, and it sets the members of an object that already exists.
A collection as the document element
You can pass a collection straight toSerialize. The document element is named from the collection type, and each item is named after its own type.
Program.cs
ArrayOf followed by the name of its items, whatever kind of collection it is. An array, a List<T> and a HashSet<T> of the same items write the same document, and each reads what the others wrote. A dictionary keeps its own kind of name. Names such as ArrayOfInvoiceLine are rarely what a document format calls for, and you can’t put [XmlRoot] on List<T>. To choose the name, make the collection a member of a class of your own and name that class with [XmlRoot].
To write or read a large sequence one item at a time instead of holding it all in memory, see Streaming. For collections whose items are of different derived types, see Polymorphism.
See also
Customize names and shape
Rename elements, write attributes, and set the order.
Polymorphism
Serialize collections whose items have different types.
XmlArrayAttribute
API reference for the wrapper attribute.
XmlArrayItemAttribute
API reference for the item attribute.