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 asMoneyorDateOnly. - The factory pattern is a class that derives from
XmlConverterFactoryand 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.
XmlConverter class directly.
Write a basic converter
The following converter reads and writes aMoney value as text such as 129.90 USD:
MoneyConverter.cs
Money.cs
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 callsRead, 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 untilreader.TokenTypeisXmlTokenType.EndElementat 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 checkreader.IsEmptyElementbefore you callreader.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 callsWrite, 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, orWriteBooleanValue. - Child elements, each with a
WriteStartElementand a matchingWriteEndElement.
Flush or dispose the writer.
Null and nil
By default, a converter never sees a nil element. For an element markedxsi: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
ThrowXmlException 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 aGeoPoint as a Lat and a Lon child element, and reads them back in any order:
GeoPointConverter.cs
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:- The converter named by
[XmlConverter]on the property or field. It applies to that member only. - The converters in
XmlSerializerOptions.Converters, in list order, by callingCanConvert. - The converter named by
[XmlConverter]on the type. - The built-in converters.
Add it to the options
Add an instance toConverters before you use the options. The converter then applies to every value of its type, wherever it appears.
Program.cs
Invoice.cs
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
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 asDateOnly, 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
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, soReadyToShip becomes ready-to-ship.
KebabCaseEnumConverterFactory.cs
KebabCaseEnumConverter.cs
Program.cs
OrderStatus and Priority.
View the complete sample on GitHub
Rules for a factory:
CreateConvertermust return anXmlConverter<T>whoseTis exactly the requested type. The serializer throwsInvalidOperationExceptionwhen it returnsnullor a converter for another type.- The serializer calls
CreateConverteronce 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 aswitchon the type.
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 inConverters, [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
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.