Skip to main content
This article is for developers who have types and code written for System.Xml.Serialization.XmlSerializer and want to move them to the XmlEssentials XmlSerializer. It lists what carries over, what changes the XML you get, and what has no counterpart. The two serializers share a class name and most attribute names, and that is on purpose: most mapped types need a different using directive and little else. The API around the types is different. The XmlEssentials XmlSerializer is a static class with generic methods and an options object, the same shape as JsonSerializer in System.Text.Json. The move also buys speed. In the project’s benchmarks, reading and writing objects is 1.8× to 5.9× faster than the old serializer, and writing into a buffer you own allocates nothing.
XmlEssentials doesn’t read System.Xml.Serialization attributes. A type that still carries the old attributes compiles, and is serialized as if it had none. Change the using directive on every file that declares a mapped type. A source-generated context that lists a type with the old [XmlInclude(typeof(T))] reports error XMLESS007.

Table of differences

Call the serializer

The old serializer is an object that you build for one type and keep. XmlEssentials has no object to build or cache: you call a static generic method, and the metadata for each type is cached by the options instance you pass.
PurchaseOrder and OrderLine use the attributes you already know. Only the using directive is different:
PurchaseOrder.cs
The complete sample fills in an order, serializes it, and reads it back:
Program.cs
The code produces the following output:
The old serializer writes the same elements for the same type. Its output differs in two places: the declaration says encoding="utf-16" because the target is a StringWriter, and the root element carries xmlns:xsi and xmlns:xsd declarations. View the complete sample on GitHub
Create one XmlSerializerOptions instance and reuse it, as you would with JsonSerializerOptions. The options hold the cached metadata, so a new instance for each call repeats the work that new XmlSerializer(typeof(T)) used to repeat.

Attribute mapping

The attributes in this table exist in both libraries under the same name. The right-hand column lists every property that differs.
[XmlInclude] in XmlEssentials is not the attribute you know. It goes on a non-public property or field to include it in serialization, as [JsonInclude] does in System.Text.Json, and it has no constructor that takes a type. To declare a derived type, use [XmlDerivedType<T>]. See Derived types.
These System.Xml.Serialization attributes have a counterpart with another name: XmlEssentials also has attributes that the old serializer has no equivalent for, such as [XmlPropertyName], [XmlPropertyOrder], [XmlRequired], [XmlConstructor], [XmlConverter], [XmlCData], and [XmlMixed]. They follow System.Text.Json where it has the same idea. See Customize names and Coming from System.Text.Json.

Differences in default behavior

The same unannotated type produces different XML in the two libraries. This Shipment class has no mapping attributes:
Shipment.cs
The following code serializes one with XmlEssentials. It turns on WriteIndented so that the output fits the page:
Program.cs
The first block is what System.Xml.Serialization.XmlSerializer writes to a StringWriter for the same object. The second block is the output of the sample. View the complete sample on GitHub

Keep the old defaults

XmlSerializerOptions.Bcl sets every option the table names for a difference: Namespaces, WriteIndented, EmptyElementStyle, IncludeFields, MemberOrder, IgnoreReadOnlyProperties, PreferredObjectCreationHandling, DefaultIgnoreCondition, DefaultCollectionMapping, UtcOffsetHandling and CharHandling. Pass it when the documents have to stay the ones the old serializer wrote, for a consumer that already reads them:
Program.cs
The output is the first block above, with encoding="utf-8":
Output
View the complete sample on GitHub XmlSerializerOptions.Bcl is read-only. The constructor in the sample gives an instance you can change, here to pin the line ending. The same options read the documents the old serializer wrote. Some things stay different under these options. Among them:
  • The declared encoding is always utf-8. See Encoding.
  • A derived type needs [XmlPolymorphic] and [XmlDerivedType] to be written with xsi:type. See Derived types.

Null values

The old serializer leaves a null reference out unless the member has IsNullable = true, and writes a nullable value type with no value as xsi:nil="true". XmlEssentials writes every null as an element with xsi:nil="true", and declares the xsi prefix on that element. To do as the old serializer does, set DefaultIgnoreCondition to XmlIgnoreCondition.WhenWritingNullReference. To leave every null member out, set it to XmlIgnoreCondition.WhenWritingNull. Either condition can go on one member with [XmlIgnore(Condition = ...)]. Reading is the same in both: a missing element leaves the property at its default, and an element with xsi:nil="true" sets it to null. For the full rules, see Null and nil.

Collections

This is the difference most likely to break a document that another system reads. The old serializer wraps every collection in an element named for the member and names each item for its type. XmlEssentials writes one element per item, named for the member, with no wrapper, because that is the closest XML shape to a JSON array and the most common shape in hand-written XML. To keep the wrapped shape for every collection, set DefaultCollectionMapping to XmlCollectionMapping.Wrapped. To keep it for one, annotate the member. The items need no attribute: they are named for their type, with the names the old serializer uses.
See Collections for every supported collection type and shape.

Encoding

XmlEssentials reads and writes UTF-8 and nothing else. Three things follow from that:
  • A string that XmlSerializer.Serialize returns has encoding="utf-8" in its declaration, even though a .NET string is UTF-16 in memory. The declaration describes the bytes you get when you save the text as UTF-8.
  • There’s no Encoding setting. To produce another encoding, transcode the UTF-8 output yourself.
  • Bytes whose declaration names another encoding are rejected. A string or a span of characters has no encoding of its own, so the encoding its declaration names isn’t checked.
The last point matters for XML that the old serializer wrote to a StringWriter and that you stored as text: its declaration says utf-16. You can read that text as it is.
Program.cs
The code produces the following output:
If you save such text as UTF-8 bytes, remove the declaration or rewrite it to say utf-8 first. A file that is really encoded as UTF-16 has to be transcoded to UTF-8 before XmlEssentials can read it; the reader reports XmlEssentials is UTF-8 only. The input is UTF-16 or UTF-32. View the complete sample on GitHub

Read documents the old serializer wrote

You don’t have to change your stored documents to move. Either read them with XmlSerializerOptions.Bcl, or map the type so that it describes the old shape: add [XmlArray] and [XmlArrayItem] where the old serializer wrapped a collection, and leave the rest alone. The xmlns:xsi and xmlns:xsd declarations on the root are read and ignored.
ArchivedShipment.cs
Program.cs
The code produces the following output:
ArchivedShipment has no Insured or Weight member, so those elements are skipped. The document has no TrackingNumber element, so the property stays null. View the complete sample on GitHub

Derived types

The old serializer learns about derived types from [XmlInclude(typeof(T))] on the base class and writes the runtime type in an xsi:type attribute. XmlEssentials uses [XmlDerivedType<T>], and [XmlPolymorphic] chooses where the type name goes. The default is the element name. To keep the xsi:type shape that your documents already have, set DiscriminatorPlacement to XmlDiscriminatorPlacement.XsiType.
Program.cs
The code produces the following output:
Apart from the xmlns:xsd declaration and the encoding name, this is the document the old serializer writes for the same object. For the other placements and for unknown type names, see Polymorphism. View the complete sample on GitHub

Types the old serializer can’t map

System.Xml.Serialization.XmlSerializer needs a public type with a public parameterless constructor and public read/write members, and it throws for any IDictionary. XmlEssentials follows the rules of System.Text.Json: it can call a constructor with parameters, set init and required members, map a record, and read and write a dictionary. A type doesn’t have to be public.
Reservation.cs
Program.cs
The code produces the following output:
A dictionary with string keys is written as one child element per entry, named for the key. A required member that is missing from the document is an XmlException on read. View the complete sample on GitHub

UTF-8 and asynchronous streams

The old serializer has no asynchronous methods, and it produces UTF-8 only when you hand it a stream. XmlEssentials works in UTF-8 throughout, so the UTF-8 overloads skip the conversion to and from a string.
Program.cs
The code produces the following output:
This output also shows the default formatting: one line, and an empty wrapped collection as <items/>. View the complete sample on GitHub The serializer also reads from and writes to ReadOnlySequence<byte>, IBufferWriter<byte>, PipeReader, PipeWriter, Utf8XmlReader, Utf8XmlWriter, and the DOM types. See Serialize, Deserialize, and Streaming.

Source generation, Native AOT, and trimming

System.Xml.Serialization.XmlSerializer generates code at run time, so it can’t be used in a Native AOT application, and its constructors are marked as unsafe for trimming. The sgen tool moves that work to build time, but still as a separate serializer assembly. XmlEssentials has a Roslyn source generator, with the same model as System.Text.Json. You declare a context class, list your types on it, and pass the generated metadata to the serializer. No reflection runs for those types.
MigrationXmlContext.cs
Program.cs
The code produces the following output:
View the complete sample on GitHub The overloads that take XmlSerializerOptions use reflection and are marked with RequiresUnreferencedCode and RequiresDynamicCode, so the compiler warns you when a trimmed or Native AOT application calls one. See Reflection versus source generation, Use source generation, and Native AOT. If you generate classes from a schema with xsd.exe, see Generate types from XSD for the build-time replacement.

What isn’t supported

These features of System.Xml.Serialization have no counterpart in XmlEssentials. Check this list before you plan a migration.

See also

Serialize

Every way to write an object as XML.

Deserialize

Every way to read XML into an object.

Configure options

The settings on XmlSerializerOptions.

Polymorphism

Derived types and where the type name goes.

Migrate from XmlReader and XmlWriter

Move low-level reading and writing code.

Coming from System.Text.Json

The API by its System.Text.Json counterparts.
API reference: