Skip to main content
This article shows how to use XmlSerializer in the CloudNimble.Text.Xml namespace to turn .NET objects into XML. XmlSerializer is a static class shaped like JsonSerializer in System.Text.Json: you call Serialize with a value and, optionally, an XmlSerializerOptions instance. The examples use reflection, which needs no setup. To serialize without reflection, for trimming and Native AOT, see Use source generation.

Serialize to a string

Call XmlSerializer.Serialize and pass the object. The method returns the XML document as a string.
Program.cs
PurchaseOrder.cs
The code produces the following output:
Notice the following:
  • The document element is named after the type, and each public property becomes a child element named after the property.
  • Elements appear in the order the properties are declared.
  • Values use the XML Schema text forms, which don’t depend on the current culture: 2026-03-14 for a DateOnly, and 129.90 for the decimal with its trailing zero kept.
  • The output has no white space between elements. To indent it, see Indent the output.
Characters that have a meaning in XML are escaped when written and restored when read:
Program.cs
The code produces the following output:
View the complete sample on GitHub

Indent the output

Set WriteIndented to true. The following example also serializes an object that holds another object and a list, so you can see how they nest.
Program.cs
Invoice.cs
The code produces the following output:
Notice the following:
  • A nested object is an element that holds the object’s own members.
  • A list has no wrapper element by default. Each item is an element named after the property, so Lines appears twice. To add a wrapper or name the items, see Serialize collections.
  • The indent is two spaces. Change it with IndentSize and IndentCharacter.
  • NewLine defaults to Environment.NewLine. The example sets it to "\n" so the output is the same on every operating system.

Control the XML declaration

By default the document starts with <?xml version="1.0" encoding="utf-8"?>. Set OmitXmlDeclaration to leave it out, or set XmlVersion to write an XML 1.1 document.
Program.cs
The code produces the following output:
The encoding is always UTF-8. The serializer writes UTF-8 bytes to every destination, and the string overload decodes those bytes at the end.
Creating an XmlSerializerOptions instance for every call is expensive, because the type metadata is cached on the instance. The examples create one per method to stay self-contained. In an application, create the options once and reuse them. See Configure XmlSerializerOptions.

Serialize to UTF-8

XML that goes to a file, a socket, or an HTTP response is UTF-8 bytes. Write the bytes directly instead of creating a string and encoding it afterward. XmlSerializer has three UTF-8 destinations.

A byte array

SerializeToUtf8Bytes returns a new array that holds the whole document.
Program.cs
The code produces the following output:

A buffer writer

Pass an IBufferWriter<byte>, such as an ArrayBufferWriter<byte> or a PipeWriter, to write into memory that the destination owns.
Program.cs
The code produces the following output:

A stream

Pass a Stream as the first argument. The serializer doesn’t close the stream.
Program.cs
The code produces the following output:
To write to a stream or a PipeWriter without blocking, use SerializeAsync, and to write a sequence of values as they arrive, use SerializeAsyncEnumerable. Both are covered in Streaming.

Serialize into a document you’re writing

Sometimes the object is only part of the document. Pass a Utf8XmlWriter and the serializer writes the object as one element at the writer’s current position.
Program.cs
The code produces the following output:
With this overload the writer’s own XmlWriterOptions decide the indentation and the declaration. The serializer options still decide names, null handling, and everything else about how the object maps to XML. The serializer doesn’t flush the writer: here, disposing the writer does.

Serialize a type known at run time

The generic overloads serialize the value as the type argument. When you hold the value as object, use the overload that takes a Type.
Program.cs
The code produces the following output:
XmlSerializer.Serialize<object>(value) writes the value as the type it has, as System.Text.Json does: the document element is named after that type. A document doesn’t record which type wrote it, so Deserialize<object> returns an XmlElement, which you can read as the type you expect with XmlSerializer.Deserialize<T>(element). To write members whose declared type is a base class, and read them back as the derived type, see Polymorphism.

Serialize to the document object model

SerializeToDocument returns a read-only XmlDocument that you can query. Dispose the document when you’re done, because it holds pooled memory.
Program.cs
The code produces the following output:
Two related methods exist. SerializeToElement returns the root XmlElement of a new document, and SerializeToNode returns a mutable XmlNode that you can edit. See Use XmlDocument and Use XmlNode.

Choose an overload

Every destination has the same four ways to say how the type is mapped. The overloads that take options are annotated with RequiresUnreferencedCode and RequiresDynamicCode, so the compiler warns when you call them from a trimmed or Native AOT application. The other two aren’t. See Reflection versus source generation.

Serialization behavior

Unless you change it with options or attributes, XmlSerializer behaves as follows:
  • Public properties that have a public getter are serialized. Fields aren’t. See Ignore properties to include fields or exclude members.
  • Each member is a child element. To write attributes or element text, see Customize names and shape.
  • Element names are the C# names, unchanged. Base class members come before derived class members.
  • A member that is null is written as an empty element marked xsi:nil="true". See Handle null values.
  • Enumeration values are written as their C# names.
  • A collection is written as repeated elements with no wrapper. See Serialize collections.
  • The output is UTF-8, has an XML 1.0 declaration, and isn’t indented.
For the types the serializer can write without a converter, see Supported types.

See also

Deserialize

Read XML into .NET objects from each kind of source.

Customize names and shape

Rename elements, write attributes and text, and set the order.

Configure options

Create, reuse, and freeze XmlSerializerOptions.

XmlSerializer

API reference for every overload.