Skip to main content
By default, XmlSerializer writes each public property as a child element named after the property. XML gives you more choices than JSON does: a value can be an element, an attribute, or the text of its parent element, and many formats care about element order. This article shows how to control each of those with attributes on your types and with XmlSerializerOptions. The attributes are in the CloudNimble.Text.Xml.Serialization namespace. Several have the same names as the attributes in System.Xml.Serialization, but the serializer only reads its own. If you’re moving existing types over, see Migrate from XmlSerializer.

Rename the root element, elements, and attributes

The following type uses four attributes:
  • [XmlRoot] names the document element.
  • [XmlAttribute] writes a property as an XML attribute, and optionally names it.
  • [XmlPropertyName] names a member, the way [JsonPropertyName] does in System.Text.Json.
  • [XmlElement] keeps a property as an element, and optionally names it.
CatalogItem.cs
Program.cs
The code produces the following output:
The same names are used to read the XML back. A name you set with an attribute is used exactly as written: a naming policy doesn’t change it. When a member has both [XmlPropertyName] and a name on [XmlAttribute], [XmlElement], or [XmlArray], [XmlPropertyName] wins. Only a simple value can be an XML attribute: a string, a number, a Boolean, a date or time, a GUID, a URI, an enumeration, and the nullable forms of those (the full list is in Supported types). [XmlAttribute] on an object or a collection makes the serializer throw a NotSupportedException the first time it uses the type. An attribute whose value is null is left out. View the complete sample on GitHub

Write a property as element text

Some XML puts a value directly inside an element that also has attributes, such as <Price Currency="USD">49.95</Price>. Mark the property that holds the value with [XmlText].
Price.cs
Program.cs
The code produces the following output:
A type can have one [XmlText] member, and that member must be a simple value. A type with an [XmlText] member can have attributes but not child elements: the serializer throws a NotSupportedException for a type that maps both. To write text as a CDATA section, use [XmlCData] instead. For text interleaved with elements, see Mixed content.

Set the order of elements

Elements are written in the order the properties are declared, with the members of a base class before the members of a derived class. To choose a different order, add [XmlPropertyOrder].
Address.cs
Program.cs
The code produces the following output:
The rules are:
  • Members with an order of zero or more come first, lowest number first.
  • Members with no order follow, in declaration order.
  • The order covers the whole type, so a member of a derived class can be placed between two members of its base class.
  • XML attributes are always written before element text, and element text before child elements. Within the attributes, the same ordering rules apply.
A negative order means “not set”. This differs from [JsonPropertyOrder] in System.Text.Json, where a negative number places a property before the unordered ones.
[XmlElement(Order = n)] and [XmlArray(Order = n)] set the same order. [XmlPropertyOrder] takes precedence when a member has both. The order affects writing only. When reading, elements are accepted in any order.

Use a naming policy for all names

To change every name at once, set a naming policy on the options instead of annotating each member. PropertyNamingPolicy applies to elements, attributes, and the document element.
Warehouse.cs
Program.cs
The code produces the following output:
Use the same options to deserialize, because the converted names are the ones the serializer looks for.

Use different policies for elements and attributes

XML formats often use one convention for elements and another for attributes. ElementNamingPolicy and AttributeNamingPolicy each override PropertyNamingPolicy for their kind of name. The element policy also names the document element.
Program.cs
The code produces the following output:

Built-in naming policies

XmlNamingPolicy has six built-in policies. A policy of null, the default, leaves names unchanged.
Program.cs
The code produces the following output:
CamelCase and PascalCase change only the first character. The other four also insert a separator at each word boundary.

Write your own naming policy

Derive from XmlNamingPolicy and override ConvertName. Return a name that is valid in XML: no spaces, and no leading digit.
LowerCaseNamingPolicy.cs
Program.cs
The code produces the following output:
The serializer calls ConvertName for the member names of a type when it first uses the type, and caches the result with the options. A policy doesn’t need to be fast, but it must return the same name every time.

Write simple values as attributes by default

When most of a format is attributes, annotating every property is noise. Set DefaultPropertyMapping to XmlPropertyMapping.Attribute to write every unannotated simple member as an XML attribute.
Program.cs
The code produces the following output:
PurchaseOrder has no attributes on it. The option applies to every type that is serialized with these options, so the simple members of nested objects become XML attributes too. Nested objects and collections themselves stay elements. To keep one member as an element, mark it with [XmlElement].

Enumeration values

An enumeration value is written as the name of the C# member. Set EnumHandling to XmlEnumHandling.Integer to write the number instead. When reading, both forms are accepted whatever the setting.
Program.cs
Parcel.cs
The code produces the following output:
The first line shows that a naming policy renames elements but not enumeration values: the value is still InTransit.

Rename a value

To write a member under another name, put [XmlPropertyName] on it. This is how you write a name that isn’t a C# identifier.
ShippingMethod.cs
Program.cs
The code produces the following output:
Names are matched the way JsonStringEnumConverter in System.Text.Json matches them:
  • The exact name is tried first. If nothing matches, a C# member name is matched without regard to case, so STANDARD is read as Standard. PropertyNameCaseInsensitive doesn’t change this: it’s about element and attribute names.
  • A name given with [XmlPropertyName] replaces the C# name and is matched exactly. NextDay and Next-Day are both rejected.
  • When two members have the same name, the first one is read.
A name can’t start or end with white space, and a name of a [Flags] member can’t contain any, because white space separates the names of a flags value. Such a name is an InvalidOperationException when the type is first used. View the complete sample on GitHub

How a name is chosen

For each member, the serializer takes the first of these that is set:
  1. The name in [XmlPropertyName].
  2. The name in [XmlAttribute], [XmlElement], or [XmlArray].
  3. The C# member name, converted by AttributeNamingPolicy or ElementNamingPolicy, or by PropertyNamingPolicy when the more specific policy is null.
For the document element, it’s the name in [XmlRoot], or else the type name converted by the element policy. The type name of a built-in type is its XML Schema name (int, string, dateTime). A collection is ArrayOf followed by the name of its items, so a List<InvoiceLine> at the root is ArrayOfInvoiceLine and an int[] is ArrayOfInt. Any other generic type has its name spelled out with the .NET names of its arguments, such as DictionaryOfStringInt32. Two members of one type can’t have the same attribute name in the same namespace, or the same element name in the same namespace. The serializer throws an InvalidOperationException when it first uses such a type, with a message such as The type maps more than one member to the element name 'Name'. To put names in an XML namespace, see Namespaces.

See also

Serialize collections

Wrap lists, name their items, and map dictionaries.

Namespaces

Put elements and attributes in XML namespaces.

Ignore properties

Leave members out of the XML.

XmlNamingPolicy

API reference for the naming policy base class.