Skip to main content
Before XmlSerializer can read or write a type, it needs a contract for it: which members become elements, which become attributes, and how each value is converted. It gets that contract in one of two ways. With reflection, it inspects the type the first time you use it. With source generation, a Roslyn generator describes the type in code while your project compiles, and the serializer builds the contract from that description without reflection. This article shows both, compares them, and helps you choose. The split mirrors System.Text.Json: XmlSerializerContext, [XmlSerializable], and XmlTypeInfo<T> play the roles of JsonSerializerContext, [JsonSerializable], and JsonTypeInfo<T>.

Reflection

Reflection is the default. Call an overload that takes a value, and optionally an XmlSerializerOptions instance, and the serializer builds the contract at run time.
Program.cs
Receipt.cs
The code produces the following output:
The last line names the resolver that built the contract. When you don’t set XmlSerializerOptions.TypeInfoResolver, the first XmlSerializer call that takes the options gives them DefaultXmlTypeInfoResolver, the reflection resolver. View the complete sample on GitHub Reflection needs nothing but the type. It has two costs:
  • The first call for each type is slow. The serializer binds the type’s members before it can read or write. See What each approach costs.
  • It doesn’t survive trimming or Native AOT. The reflection overloads are marked [RequiresUnreferencedCode] and [RequiresDynamicCode], so the compiler warns when you call them from a trimmed or AOT-published application. See Publish with Native AOT.

Source generation

With source generation, you declare a partial class that derives from XmlSerializerContext and list your types on it. The generator, which ships inside the XmlEssentials package, fills in the class with metadata for each type and with code that writes it.
OrderXmlContext.cs
You then pass the generated type info to the serializer:
Program.cs
Order.cs
The code produces the following output:
View the complete sample on GitHub For the full procedure, see How to use source generation.

Compare the two

Both approaches read and write with the same engine, so they produce the same documents for the same options. The source generation column describes the Default and Metadata generation modes. A context in the Serialization mode only writes, with the options it was compiled for. See Source-generation modes.

What each approach costs

The numbers below come from the graph benchmark in the repository: a Customer object with two addresses, 20 line items, and four tags, on .NET 11, in the run described on the benchmarks page. System.Xml.Serialization.XmlSerializer and System.Text.Json read and write the same object graph, the second one as JSON. What to notice:
  • The first reflection call costs about 0.6 ms and 80 KB for this graph. That’s the time the serializer spends binding the type’s members. It’s paid once for each type and each XmlSerializerOptions instance, which is why you create one options instance and reuse it.
  • Both approaches are about three times as fast as the System.Xml serializer on this graph: 3.3× to read, and 3.0× to 3.6× to write.
  • After the first call, both approaches read with the same engine. A generated context needs no reflection, is safe for trimming and Native AOT, and in the Default mode has a write fast path. Neither approach allocates when writing.
  • The benchmark doesn’t measure a first call through a generated context. On that call, the serializer creates the type info from the generated metadata, and it reflects over no members to do so.
For the full tables, see Benchmarks.

Interceptors

The package also turns on interceptors. When a context in your project lists a type, the generator redirects calls that pass no options and no type info for that type to the generated context. You don’t change the call.
Program.cs
ShippingXmlContext.cs
The code produces the following output:
The first two calls look like reflection calls, but the generator rewrote them to use ShippingXmlContext.Default.Shipment. The document is the one the reflection resolver would write. The third call passes options, so it isn’t redirected: your options decide how it runs, and the last line shows that their resolver is still the one they had. View the complete sample on GitHub The generator intercepts two shapes of call: XmlSerializer.Serialize<T>(value) and XmlSerializer.Deserialize<T>(input), where T is a type that a context in the same project lists or reaches through the members of a listed type. The input can be any of the kinds Deserialize<T> accepts: a string, a span of characters, UTF-8 bytes, a sequence, a stream, a Utf8XmlReader, an XmlDocument, an XmlElement, or an XmlNode. Interceptors are on when the InterceptorsNamespaces build property contains CloudNimble.Text.Xml.Generated, which the package’s build file adds for you. Only contexts declared in your source code with [XmlSerializable] redirect calls. The context generated from an .xsd file is itself generated code, which the generator doesn’t see, so for the classes of a schema, pass the context’s type info. A call is never intercepted when it passes an XmlSerializerOptions argument, even null. Options say how the call is to run: which resolver, which converters, which names. The call runs as you wrote it, and your options aren’t changed. To use a generated context with your own options, create the context from them and pass its type info: new MyContext(options).Order.
An intercepted call uses the type info of the context’s Default instance, with the options that the [XmlSourceGenerationOptions] attribute on the context seeds. When two contexts list the same type, the call goes to one of them.To keep full control, pass an XmlTypeInfo<T> or a context yourself. Those calls are never intercepted.
In a project that is published trimmed or with Native AOT, write the call with the type info or the context. The trimming and Native AOT analyzers look at the method your code names, so a call that passes only a value reports IL2026 and IL3050 even when the generator redirects it. XmlEssentials doesn’t hide those warnings. See Publish with Native AOT.

How to choose

Use reflection when:
  • You’re writing an application that isn’t trimmed or published with Native AOT, and the first-call cost doesn’t matter.
  • You want no setup: there’s no context to declare and no types to list.
Use source generation when:
  • You publish with trimming or Native AOT. It’s the only approach that works there.
  • Startup time matters, for example in a command-line tool or a serverless function, and you don’t want the serializer to reflect over your types at run time.
  • You want mapping mistakes reported by the compiler.
You can mix the two: use a generated context for the types you list on it and reflection for the rest. Custom converters, [XmlDerivedType], ReferenceHandler, and every option work with both.

See also

Use source generation

Declare a context and call the serializer with it, step by step.

Source-generation modes

What the generator writes in each XmlSourceGenerationMode.

Publish with Native AOT

Set up a project so that it trims and compiles ahead of time.

Benchmarks

Every measured row, with the method behind it.