Skip to main content
Source generation describes your types to the serializer at compile time. You declare a context class, the generator fills it in with metadata for each type, and you pass its type info to XmlSerializer. The serializer then reads and writes without reflecting over your types. Use it when you publish with trimming or Native AOT, or when you want mapping mistakes reported by the compiler. To decide between the two approaches, see Reflection versus source generation. The API mirrors System.Text.Json source generation: XmlSerializerContext, [XmlSerializable], [XmlSourceGenerationOptions], and XmlTypeInfo<T> correspond to JsonSerializerContext, [JsonSerializable], [JsonSourceGenerationOptions], and JsonTypeInfo<T>.

Generate and use a context

The generator is part of the XmlEssentials package. There’s no second package to install.
1

Install the package

Add XmlEssentials to the project that holds your types:
2

Declare a partial context class

Create a class that derives from XmlSerializerContext and mark it partial. Leave the body empty. The generator writes the other half.
OrderXmlContext.cs
The class can be public or internal.
3

List your root types

Add one [XmlSerializable] attribute for each type you pass to the serializer. The generator follows the properties of each type, so Order brings in OrderLine without a second attribute. The type is a type argument of the attribute, as in [XmlSerializable<Order>], so the compiler checks it. It can be any closed type, including an array ([XmlSerializable<Order[]>]) or a collection ([XmlSerializable<List<Order>>]).
Order.cs
4

Pass the generated type info to the serializer

The generator adds a static Default property to the context and one XmlTypeInfo<T> property for each type, named after the type. Pass that property to an XmlSerializer overload:
Program.cs
The code produces the following output:
Deserialize needs no type argument here: the compiler infers Order from the type info.
CreateOrder builds the order that every example in this article uses: number 1042 for Ada, with two lines. View the complete sample on GitHub

What the generator adds to your class

For a context named OrderXmlContext that lists Order, the generated half of the class contains: To give a property a different name, for example when two listed types share a name, set TypeInfoPropertyName:
OrderLineXmlContext.cs
Program.cs
The code produces the following output:
The property name changes. The element name doesn’t.

Pass the context instead of the type info

Most serializer methods that take an XmlTypeInfo<T> also have an overload that takes the context: the ones for strings, UTF-8 bytes, streams, buffer writers, Utf8XmlReader, Utf8XmlWriter, and DOM nodes. The serializer then calls GetTypeInfo for you. The PipeReader and IAsyncEnumerable<T> methods take type info only.
Program.cs
The code produces the following output:
Prefer the type info overloads when you know the type at compile time. They skip the lookup, and a type that isn’t in the context is a compiler error instead of a surprise at run time.
A generated context answers GetTypeInfo for the types it lists and for every type reachable from them: classes, structs, and records, and the collection, dictionary, enumeration, and nullable types their members use. It also answers for a built-in value, an XML value such as XmlElement, object, and a type with [XmlConverter]. For any other type it returns null, and the serializer throws NotSupportedException. It never maps the members of a type through reflection, so list every class, struct, and record you serialize, and list a collection or array type too when you serialize it as the document element.

Set options

A context is bound to one XmlSerializerOptions instance, which you read from its Options property. You choose those options at compile time, at run time, or both.

At compile time

Add [XmlSourceGenerationOptions] to the context. Default and the parameterless constructor use these values.
CamelCaseOrderXmlContext.cs
Program.cs
The code produces the following output:
Line keeps its capital because [XmlElement("Line")] names it explicitly. A naming policy changes only the names it derives from member and type names. GenerationMode chooses what the generator writes. See Source-generation modes. Every other property of the attribute sets the XmlSerializerOptions property of the same name on the default options: The naming policies are the XmlKnownNamingPolicy values. For any other setting, such as NewLine, Converters, or ReferenceHandler, pass your own XmlSerializerOptions to the context’s constructor.

At run time

Pass an XmlSerializerOptions instance to the context’s constructor. The context makes itself the options’ TypeInfoResolver, and the default options from the attribute aren’t used: constructor options win.
Program.cs
The code produces the following output:
Create the context once and keep it, as you would an options instance. The constructor throws InvalidOperationException when the options are read-only, which includes XmlSerializerOptions.Default, Web, Strict, and Bcl.

How a context applies your options

The metadata in a generated context describes each type as it’s declared. The serializer applies your options to that metadata when it creates the type info, as the reflection resolver does. Every XmlSerializerOptions setting applies, and a generated context writes and reads the same documents as the reflection resolver for the same options. That includes:
  • The naming policies, DefaultPropertyMapping, IncludeFields, IgnoreReadOnlyProperties, and IgnoreReadOnlyFields.
  • DefaultIgnoreCondition, RespectNullableAnnotations, PreferredObjectCreationHandling, UnknownTypeHandling, UnmappedMemberHandling, PropertyNameCaseInsensitive, and NumberHandling.
  • ReferenceHandler. See Preserve references.
  • Converters, and [XmlConverter] on a type or 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. See Custom converters.
A generated context also supports derived types, mixed content, extension data, XmlObjectCreationHandling.Populate, init-only and required members, non-public members marked [XmlInclude], and a non-public constructor marked [XmlConstructor]. In the default mode, a context also has a write fast path for each type: generated code that writes the type directly, with its names and its choice of members compiled in from [XmlSourceGenerationOptions]. The serializer uses it when your options agree with what it was compiled for, and writes from the metadata when they don’t. The document is the same either way. For the conditions, see When the fast path writes.
A context in XmlSourceGenerationMode.Serialization has the fast path and no metadata. It writes with the options it was compiled for, and it can’t read. See Source-generation modes.

Use more than one context

A project can hold any number of contexts, for example one for each feature area. Take the type info for each type from the context that lists it:
Program.cs
The code produces the following output:
View the complete sample on GitHub
You can add several generated contexts to XmlSerializerOptions.TypeInfoResolverChain. Each context answers for the types it lists and returns null for the others, so the next context in the chain is asked. The options that hold the chain decide how every type is written: each context creates its type info for those options, not for its own. Every setting of those options applies, as it does when you pass options to a context’s constructor.

Understand the diagnostics

The generator reports problems as compiler diagnostics in the XmlEssentials category. All are errors except XMLESS011, which is information, and XMLESS018, which is a warning.

See also

Reflection vs. source generation

What each approach does and costs.

Source-generation modes

What the generator writes in each mode, and what each mode can do.

Publish with Native AOT

The project settings that go with a generated context.

Generate types from an XSD

Let the generator write the classes too.