Skip to main content
JSON has an array syntax. XML doesn’t: a list is a run of sibling elements, and formats differ on whether those siblings sit inside a wrapper element. This article shows the shape 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
The code produces the following output:
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.
When reading, the repeated elements don’t have to be next to each other. Every element with the member’s name is added to the same collection, in document order. View the complete sample on GitHub

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
The code produces the following output:
[XmlArrayItem] names the items of a wrapped collection only: one that has [XmlArray], or one that DefaultCollectionMapping wraps. On a collection with no wrapper, it has no effect, and the items keep the member’s name.

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
The code produces the following output:
Both names are optional. [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
The code produces the following output:
An item is named for its type: the XML Schema name for a built-in type, such as 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, set XmlSerializerOptions.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 code produces the following output:
  • 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.Bcl sets Wrapped, along with the other settings that match System.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
The code produces the following output:
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, or WhenWritingDefault, on the member or as DefaultIgnoreCondition, a null wrapped collection is left out.
A null item inside a collection is written as an element marked xsi:nil="true" and reads back as null.
If the difference between an empty collection and a missing one matters to the consumer of your XML, use a wrapper.

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 a Key element followed by a Value element.
AppSettings.cs
Program.cs
The code produces the following output:
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 string key 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 Key itself (an element named Key starts a pair when reading), and for every key that isn’t a string, such as an int or a Guid.
  • A null value is written as an element marked xsi:nil="true", whatever the ignore condition, and reads back as null. 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
The code produces the following output:
A policy can’t be reversed, so the keys you read are the keys in the XML. 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 implements IEnumerable<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
The code produces the following output:
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 is XmlObjectCreationHandling.Replace, and it is what System.Text.Json does. To keep the value a member already holds and add to it, use XmlObjectCreationHandling.Populate:
When a member is populated:
  • 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 null is given a new instance when it has a setter.
  • An element marked xsi:nil="true" sets a member that has a setter to null. For a member with no setter, the serializer throws an InvalidOperationException.
The following can’t be populated. 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> or IReadOnlyList<T>.
  • A collection or dictionary class with no public parameterless constructor, such as ReadOnlyCollection<T>, and a collection class that doesn’t implement ICollection<T>, other than Stack<T> and Queue<T>.
  • A member marked [XmlIgnore(Condition = XmlIgnoreCondition.WhenReading)], which is never read.
  • A single value such as a string or a number.
  • A value that has a custom converter, and mixed content.
  • A polymorphic type.
  • A value type with no setter.
Two more limits apply:
  • 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.
  • Populate can’t be combined with ReferenceHandler. A type with a member to populate throws an InvalidOperationException.
A member declared as 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 to Serialize. The document element is named from the collection type, and each item is named after its own type.
Program.cs
The code produces the following output:
A collection at the root is named 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.