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
CallXmlSerializer.Serialize and pass the object. The method returns the XML document as a string.
Program.cs
PurchaseOrder.cs
- 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-14for aDateOnly, and129.90for thedecimalwith its trailing zero kept. - The output has no white space between elements. To indent it, see Indent the output.
Program.cs
Indent the output
SetWriteIndented 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
- 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
Linesappears twice. To add a wrapper or name the items, see Serialize collections. - The indent is two spaces. Change it with
IndentSizeandIndentCharacter. NewLinedefaults toEnvironment.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
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 astring 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
A buffer writer
Pass anIBufferWriter<byte>, such as an ArrayBufferWriter<byte> or a PipeWriter, to write into memory that the destination owns.
Program.cs
A stream
Pass aStream as the first argument. The serializer doesn’t close the stream.
Program.cs
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 aUtf8XmlWriter and the serializer writes the object as one element at the writer’s current position.
Program.cs
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 asobject, use the overload that takes a Type.
Program.cs
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
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
nullis written as an empty element markedxsi: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.
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.