Skip to main content
Native AOT compiles your application to machine code at publish time, and trimming removes the code it doesn’t reach. Neither can follow code that inspects types with reflection at run time. This article shows how to use XmlEssentials in such an application: which parts work as they are, which serializer overloads to call, and how to turn the reflection path off so that a mistake fails at once instead of in production. The approach is the one System.Text.Json uses: a source-generated context, overloads that take type info, and an IsReflectionEnabledByDefault feature switch.

What works without any setup

The library is built with IsAotCompatible, and it has no dependency on System.Xml. These parts use no reflection and need nothing from you: Only XmlSerializer needs care, because its default way of learning about a type is reflection.

Set up a project

1

Declare a context for the types you serialize

In your project, add a partial class that derives from XmlSerializerContext, with one [XmlSerializable] attribute for each root type. Every generation mode is safe for trimming and Native AOT.
OrderXmlContext.cs
For the details, see How to use source generation.
2

Call the overloads that take type info or a context

In your code, replace each call that passes only a value, or a value and options, with one that passes the generated XmlTypeInfo<T> or the context.
Program.cs
The code produces the following output:
3

Turn on Native AOT

In the project file, set PublishAot. This also turns on the trim and AOT analyzers, so the compiler warns about unsafe calls while you work.
MyApp.csproj
To trim without compiling ahead of time, set PublishTrimmed instead.
4

Turn off the reflection fallback

In the project file, set the IsReflectionEnabledByDefault feature switch to false:
MyApp.csproj
See The reflection switch for what this changes.
5

Publish and run

From the project folder, publish the application, and then run the native executable to check that it behaves as the JIT-compiled build does:
Fix every IL2026 and IL3050 warning the build reports. Each one marks a call that needs reflection.
View the complete sample on GitHub

Which overloads are safe

Every XmlSerializer method comes in up to three forms. The form that takes XmlSerializerOptions uses reflection and is marked [RequiresUnreferencedCode] and [RequiresDynamicCode]. The forms that take an XmlTypeInfo<T> or an XmlSerializerContext carry no annotations. The overloads that take a Type and a context, such as Serialize(object? value, Type inputType, XmlSerializerContext context), are safe too.
To write to a PipeWriter in a trimmed or Native AOT application, serialize to the pipe’s stream, pipeWriter.AsStream(), with a type info overload.
The context overloads work with any destination that has one. The following example writes to a stream and reads it back:
Program.cs
The code produces the following output:
View the complete sample on GitHub

The reflection switch

XmlSerializer.IsReflectionEnabledByDefault is a feature switch named CloudNimble.Text.Xml.XmlSerializer.IsReflectionEnabledByDefault. It’s true unless you set it to false. When it’s true, an XmlSerializerOptions instance with no TypeInfoResolver is given DefaultXmlTypeInfoResolver, the reflection resolver, by the members that need reflection: the XmlSerializer methods that take options, XmlSerializerOptions.GetConverter, MakeReadOnly(populateMissingResolver: true), and the shared instances Default, Web, Strict, and Bcl. Each of them carries the trimming and Native AOT warnings. TypeInfoResolver itself, GetTypeInfo, the overloads that take type info or a context, and everything a generated context calls carry none, and they never bring the reflection resolver in. When it’s false:
  • XmlSerializerOptions.TypeInfoResolver stays null until you set it.
  • A reflection overload called with such options throws InvalidOperationException with the message “Reflection-based XML serialization is disabled. Set TypeInfoResolver, or use an overload that takes an XmlTypeInfo or XmlSerializerContext.”
  • The overloads that take type info or a context work as before.
Setting the switch in the project file with Trim="true" also tells the trimmer the value, so it can treat the property as a constant.
The switch covers options that have no resolver. A generated context uses no reflection either. It creates every type it lists or reaches with generated code: classes, structs, and records, and the collection, dictionary, enumeration, and nullable types their members use. For a type it neither lists nor reaches, GetTypeInfo returns null and the serializer throws NotSupportedException, unless the type is a built-in value, an XML value such as XmlElement, or object. That includes a collection type no listed type uses, such as a List<int> that you serialize as the document element. List every type you pass to the serializer on a context, collections and arrays included, and prefer the XmlTypeInfo<T> overloads, which can only name a listed type.

What the package adds to your build

The XmlEssentials package carries three things: The package doesn’t set PublishAot, PublishTrimmed, or the reflection switch. Those are your choices.

Limits to know about

A generated context applies every option and supports derived types, reference handling, and custom converters, as the reflection resolver does. See How a context applies your options. These limits apply:
  • A context in the Serialization mode only writes. A read through it throws InvalidOperationException. Use the Default or Metadata mode for a context that reads. See Source-generation modes.
  • Custom converter factories often need reflection themselves. A factory that calls MakeGenericType isn’t safe. See Custom converters.
  • Schemas stay at build time. Types generated from an .xsd file come with their own context, and the schema isn’t read at run time. Pass that context’s type info: calls for those types aren’t redirected by interceptors. See Generate types from an XSD.

Working examples

The repository has two projects that publish with Native AOT:
  • CloudNimble.XmlEssentials.Tests.Aot runs with the reflection switch off. It round-trips types through a generated context and types generated from schemas, walks a document with Utf8XmlReader, and exercises derived types, reference handling, populating, the naming policies, and the Bcl defaults through generated metadata. It also checks that a reflection call throws.
  • CloudNimble.XmlEssentials.Samples.Cli is a command-line tool that parses and serializes XML.

See also

Use source generation

Declare a context and call the serializer with it.

Reflection vs. source generation

What each approach does and costs.

Generate types from an XSD (preview)

Classes and a context from a schema, with no reflection. In preview.

Security

Limits and defaults for reading untrusted XML.