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 theXmlEssentials 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 The class can be
XmlSerializerContext and mark it partial. Leave the body empty. The generator writes the other half.OrderXmlContext.cs
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 The code produces the following output:
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
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 namedOrderXmlContext 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
Pass the context instead of the type info
Most serializer methods that take anXmlTypeInfo<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
Set options
A context is bound to oneXmlSerializerOptions 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
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 anXmlSerializerOptions 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
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. EveryXmlSerializerOptions 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, andIgnoreReadOnlyFields. DefaultIgnoreCondition,RespectNullableAnnotations,PreferredObjectCreationHandling,UnknownTypeHandling,UnmappedMemberHandling,PropertyNameCaseInsensitive, andNumberHandling.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.
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
Understand the diagnostics
The generator reports problems as compiler diagnostics in theXmlEssentials 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.