XmlSerializerContext can hold two things for each type. Metadata describes the type’s members. A write fast path is generated code that writes the type directly. XmlSourceGenerationMode chooses which of the two the generator writes. This article explains what each mode produces and when to use it.
The enumeration has the same members as JsonSourceGenerationMode in System.Text.Json, and they mean the same things.
How a generated context works
The metadata is a set of values: anXmlObjectInfoValues<T> for the type, an XmlPropertyInfoValues<TValue> for each member, and an XmlParameterInfoValues for each constructor parameter. XmlMetadataServices.CreateObjectInfo turns them into type info. These types mirror JsonObjectInfoValues<T>, JsonPropertyInfoValues<T>, and JsonMetadataServices in System.Text.Json.
The serializer reads and writes from that type info with the same engine the reflection resolver uses, so a generated context gives the same result as the reflection resolver. No generated code reads XML.
The members of a type are never reflected over. The getters and setters in the metadata are generated delegates. init-only and required members, non-public members marked [XmlInclude], and a non-public constructor marked [XmlConstructor] are reached through [UnsafeAccessor].
Choose a mode
SetGenerationMode on [XmlSourceGenerationOptions]. Without the attribute, a context uses Default.
MetadataOrderXmlContext.cs
SerializationOrderXmlContext.cs
XmlSourceGenerationMode has these members:
Metadata | Serialization is the same as Default.
Whatever the mode, the context has the same public shape: Default, the two constructors, one XmlTypeInfo<T> property for each type, and GetTypeInfo. You can change the mode without changing the code that calls the serializer.
[XmlSerializable] also has a GenerationMode property. It overrides the mode of the context for the type the attribute lists. Default on the attribute leaves the mode of the context in place. The types that the listed type reaches use the mode of the context.See the difference
The following example takes the type info for the sameOrder type from a context in each mode. It writes an order with all three, and then reads it back with each.
Program.cs
- All three modes write the same document.
- The type info of the
DefaultandMetadatacontexts lists the three members ofOrderinProperties, and both contexts read the document. - The type info of the
Serializationcontext lists no members.DeserializethrowsInvalidOperationException, and the message names the modes that can read.
When the fast path writes
The fast path has its element and attribute names and its choice of members compiled in. In theDefault and Serialization modes, the serializer uses it when the options agree with what it was compiled for:
- The element and attribute naming policies,
DefaultPropertyMapping,DefaultCollectionMapping, andIncludeFieldsequal the values that[XmlSourceGenerationOptions]on the context declares. The policies areElementNamingPolicyandAttributeNamingPolicy, each falling back toPropertyNamingPolicy. IgnoreReadOnlyPropertiesandIgnoreReadOnlyFieldsarefalse.DefaultIgnoreConditionisn’tWhenWritingNullReference.CharHandling,MemberOrder, andUtcOffsetHandlinghave their default values:Character,PropertiesFirst, andWriteOffset.- The options have no
ReferenceHandler. - The options hold no custom converter for the type, or for a simple type that the fast path writes directly.
XmlSerializerDefaults.Bcl change several of these, so a Default context created from them always writes from the metadata.
With any other options, a Default context writes from the metadata, and the document is the one the reflection resolver writes. A Serialization context has no metadata, so the write throws InvalidOperationException. That includes the context’s own Default instance when [XmlSourceGenerationOptions] sets one of the values above, such as IgnoreReadOnlyProperties = true.
The generator writes no fast path for a type with any of the following, and it reports no diagnostic:
- Derived types declared on the type.
- A member that declares derived types, or whose type or item type does.
- A member with
[XmlConverter]. - A member with more than one
[XmlElement<T>]or more than one[XmlArrayItem<T>]: a choice of elements. - A member whose
[XmlElement]or[XmlArray]setsNamespace = "", and a wrapped collection whose[XmlArrayItem]names a namespace. - Mixed content (
[XmlMixed]). - Extension data (
[XmlExtensionData]). - A member that isn’t accessible from the context.
- Two members with the same C# name in the type’s hierarchy.
Default mode, the serializer writes such a type from the metadata. In the Serialization mode, such a type has neither a fast path nor metadata, so it can’t be written.
Inspect the contract
In theDefault and Metadata modes, you can read the contract from the type info: the name of the document element and one XmlPropertyInfo for each member, in the order the members are written. The following example uses the Metadata context. A Default context gives the same list.
Program.cs
Compare the modes
The mode applies to object types: the classes, structs, and records that are mapped member by member. For an enumeration, a collection, a dictionary, or a nullable value that the context lists or reaches, the generated code creates the built-in converter with every type argument named, in every mode.
When to use each mode
UseDefault unless you have a reason not to. The context reads and writes, applies every option, and writes through the fast path whenever the options allow it.
Use Metadata when you don’t want the fast path. The generator writes metadata only, and the serializer reads and writes from it. The documents are the same as in the Default mode.
Use Serialization for a context that only writes, always with the options that its [XmlSourceGenerationOptions] attribute declares, and whose types all have a fast path. The generator writes no metadata. A read, a write with other options, and a write of a type with no fast path throw InvalidOperationException.
Under Native AOT, call the XmlSerializer overloads that take an XmlTypeInfo<T> or a context, in every mode. See Publish with Native AOT.
See also
Use source generation
Declare a context and call the serializer with it.
Reflection vs. source generation
What each approach does and costs.
Custom converters
Write a converter, and use it with a generated context.
Publish with Native AOT
The project settings that go with a generated context.