Skip to main content
A converter is a class that reads one type from XML and writes it back. XmlSerializer has built-in converters for the supported types. You write your own when the XML form of a value isn’t the one the serializer would choose: a value with its own text format, a type you can’t annotate, or a built-in type that a partner writes differently. The design follows System.Text.Json: XmlConverter<T>, XmlConverterFactory, and XmlConverterAttribute correspond to JsonConverter<T>, JsonConverterFactory, and JsonConverterAttribute. If you’ve written a JSON converter, the main new idea is that a converter works on an element, which has a start tag and an end tag, instead of a single token.

Choose a pattern

There are two patterns, as in System.Text.Json:
  • The basic pattern is a class that derives from XmlConverter<T> and handles one type. Use it for a type such as Money or DateOnly.
  • The factory pattern is a class that derives from XmlConverterFactory and creates a converter for each type it’s asked about. Use it for a family of types, such as every enumeration or every closed form of a generic type.
You can’t derive from the non-generic XmlConverter class directly.

Write a basic converter

The following converter reads and writes a Money value as text such as 129.90 USD:
MoneyConverter.cs
Money.cs
View the converter on GitHub To follow the basic pattern:
1

Derive from XmlConverter<T>

Create a class that derives from XmlConverter<T>, where T is the type to read and write. Give it a public parameterless constructor if you plan to name it in [XmlConverter].
2

Override Read

Read the element the reader is on and return the value. Follow the reader contract: the reader starts on the element’s start tag and you leave it on the element’s last token.
3

Override Write

Write the content of the element: text, or child elements. The serializer has already written the start tag and writes the end tag after you return.
4

Leave CanConvert as it is

The default implementation returns true when the requested type is exactly T, and a basic converter can serve only that type. If you widen CanConvert to accept other types, the serializer throws InvalidOperationException when it asks the converter for one of them. To handle several types, write a factory.

The contract a converter keeps

A converter shares the reader and the writer with the serializer. The serializer continues from where you stop, so a converter that reads too little or too much breaks the members that follow it.

In Read

When the serializer calls Read, the reader is on the start tag of the element that holds the value. reader.TokenType is XmlTokenType.StartElement, and you can read the element’s attributes. When you return, the reader must be on the last token of that same element:
  • For an element with an end tag, such as <Total>129.90 USD</Total> or <Total></Total>, that’s the end tag. Read until reader.TokenType is XmlTokenType.EndElement at the element’s own depth.
  • For an empty-element tag, such as <Total/>, that’s the start tag itself. The reader produces no end-tag token for it, so check reader.IsEmptyElement before you call reader.Read(), and return without reading.
MoneyConverter.Read shows both cases. Don’t read past the end tag: the next token belongs to the serializer. Three members of Utf8XmlReader do most of the work in a converter: Utf8XmlReader is a ref struct, and Read receives it by reference. Pass it by ref to any helper method, as the next section does, or the helper advances a copy.

In Write

When the serializer calls Write, the writer is inside the element that holds the value. The start tag is written, and the end tag follows after you return. Write the content only:
  • A text value, with WriteStringValue, WriteNumberValue, or WriteBooleanValue.
  • Child elements, each with a WriteStartElement and a matching WriteEndElement.
Close every element you open. Don’t write the value’s own element, and don’t call Flush or dispose the writer.

Null and nil

By default, a converter never sees a nil element. For an element marked xsi:nil="true", the serializer returns null without calling Read, and throws XmlException when T can’t be null. To handle nil elements yourself, override HandleNull to return true. Read is then called for nil elements too, and reader.GetNil() tells you whether the element is one.

Errors

Throw XmlException when the content isn’t valid for the type, as MoneyConverter.Parse does. That’s the exception the built-in converters throw for a value they can’t parse.

Read and write child elements

A converter isn’t limited to text. The following one writes a GeoPoint as a Lat and a Lon child element, and reads them back in any order:
GeoPointConverter.cs
Each child element is read to its own end tag, by ReadNumber or by Skip, before the outer loop reads again. That keeps the outer loop’s test simple: the next EndElement it sees is the end of the GeoPoint element. The same rule you keep for the serializer, you keep for yourself. View the converter on GitHub

Register a converter

The serializer looks for a converter in this order and uses the first match:
  1. The converter named by [XmlConverter] on the property or field. It applies to that member only.
  2. The converters in XmlSerializerOptions.Converters, in list order, by calling CanConvert.
  3. The converter named by [XmlConverter] on the type.
  4. The built-in converters.
Because the options list comes before the type, a converter you add there replaces a built-in converter and overrides an attribute on the type. An attribute on a member overrides both.

Add it to the options

Add an instance to Converters before you use the options. The converter then applies to every value of its type, wherever it appears.
Program.cs
Invoice.cs
The code produces the following output:
MoneyConverter wrote the Total element. CompactDateConverter, shown in Replace a built-in converter, wrote both dates. The options become read-only the first time the serializer uses them. Adding a converter after that throws InvalidOperationException. View the complete sample on GitHub

Put an attribute on the type

Apply [XmlConverter] to a class, struct, or enumeration that you own. Every options instance then uses the converter, with nothing to register.
GeoPoint.cs
Program.cs
The code produces the following output:
The converter is the type argument of the attribute. It must derive from XmlConverter and have a public parameterless constructor, and the compiler checks both. The serializer creates one instance for each options instance when the attribute is on a type, and one for each member when it is on a property or field. View the complete sample on GitHub
[XmlConverter] can also be applied to a property or a field, as [JsonConverter] can in System.Text.Json. The converter then reads and writes that member only, and the other members of the same type keep their usual converter. The converter handles the whole value: a collection member isn’t taken apart into items, and the member may be mapped with [XmlAttribute] or [XmlText]. A converter for T also serves a member of type T?. The reflection resolver and a source-generated context both apply it.

Replace a built-in converter

A converter for a type the serializer already handles, such as DateOnly, int, or string, has more to do, because those types can also appear in attributes and as the text of an element. Override three more methods: The default implementation of each throws InvalidOperationException.
CompactDateConverter.cs
In the invoice output above, Issued="20261123" came from WriteAsAttribute and <Due>20261223</Due> from Write. View the converter on GitHub
A type that has a converter can be an attribute or the text of an element, whether the converter is in Converters or named by [XmlConverter]. The serializer then calls the converter’s WriteAsAttribute, ReadAsAttribute, and ReadLexical methods, so override them. A converter that overrides only Read and Write throws InvalidOperationException with the message “Converter ’…’ does not support attributes.” when it is asked for an attribute. A type with no converter that isn’t a simple value still can’t be an attribute: the serializer throws NotSupportedException with the message “Member ’…’ is mapped as an XML attribute. Complex types cannot be attributes.”

Write a converter factory

A factory decides at run time which converter a type gets. The following factory handles every enumeration. It writes member names in kebab case, so ReadyToShip becomes ready-to-ship.
KebabCaseEnumConverterFactory.cs
KebabCaseEnumConverter.cs
Register the factory as you would a converter:
Program.cs
The code produces the following output:
One factory served two enumerations, OrderStatus and Priority. View the complete sample on GitHub Rules for a factory:
  • CreateConverter must return an XmlConverter<T> whose T is exactly the requested type. The serializer throws InvalidOperationException when it returns null or a converter for another type.
  • The serializer calls CreateConverter once for each type and options instance, and keeps the result. A factory named by [XmlConverter] on a property or field is asked once for that member.
  • A factory that uses MakeGenericType, as this one does, isn’t safe for Native AOT. In an AOT application, return converters you construct directly, for example from a switch on the type.
This factory is a teaching example. To change how enumerations are written without a converter, see XmlSerializerOptions.EnumHandling in How to configure XmlSerializerOptions.

Use a converter with source generation

A source-generated context applies custom converters as the reflection resolver does, with the same result. That covers a converter in Converters, [XmlConverter] on a type, and [XmlConverter] on a member. A converter you supply for a type, in the options or with the attribute on the type, is used in place of the generated metadata for that type. The context needs no special setup. Create it from the options that hold the converter, and pass its type info to the serializer:
QuoteXmlContext.cs
Program.cs
The code produces the following output:
View the complete sample on GitHub The context here is in the default generation mode, and the Metadata mode works the same way. See Source-generation modes.

Keep converters safe to share

The serializer keeps one converter instance for each type and options instance, and one for each member that names a converter with [XmlConverter], and calls it from every thread that uses those options. Don’t store state from one call in a field. Keep a converter immutable after you construct it.

See also

Use Utf8XmlReader

Tokens, values, and attributes, as a converter’s Read sees them.

Use Utf8XmlWriter

The write methods a converter’s Write calls.

Supported types

The types that have a built-in converter.

Polymorphism

Derived types without a converter.