Serialize collection contracts with XmlSerializer

A sequence-producing interface describes how to enumerate values. It does not necessarily describe how an XML serializer should construct and populate an object. Give an XML boundary a concrete, deliberate contract, even when the application's internal operations use IEnumerable<T>.

An array DTO is often enough. It also makes it practical to distinguish an omitted element, an empty collection and an explicit xsi:nil value. Those XML shapes should follow the receiving system's contract rather than an assumption about what a property initializer will do.

Run null, empty and populated round trips

Use the .NET 10 SDK. Create a console project in a new directory, then replace Program.cs with the example below.

Plain text
dotnet new console --framework net10.0
dotnet run

Run dotnet run after saving the replacement. No additional packages are required.

C#
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;

var serializer = new XmlSerializer(typeof(Envelope));
var cases = new[] {
	new Envelope { Items = null },
	new Envelope(),
	new Envelope { Items = new[] { "bolt", "nut" } }
};
foreach (var value in cases) {
	using var writer = new StringWriter();
	serializer.Serialize(writer, value);
	var xml = writer.ToString();
	var element = XDocument.Parse(xml).Root?.Element("Items");
	var nil = element?.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"))?.Value == "true";
	var shape = nil ? "nil" : $"{element?.Elements().Count() ?? 0} item(s)";
	Console.WriteLine($"Round-trip {Describe(value)}: {shape} -> {Describe(Read(xml))}");
}
Console.WriteLine($"Missing element: {Describe(Read("<Envelope />"))}");
Console.WriteLine($"Empty element: {Describe(Read("<Envelope><Items /></Envelope>"))}");
Console.WriteLine($"Nil element: {Describe(Read("<Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Items xsi:nil='true' /></Envelope>"))}");

Envelope Read(string xml) {
	using var reader = new StringReader(xml);
	return (Envelope)(serializer.Deserialize(reader) ?? throw new InvalidOperationException("Missing document root."));
}

static string Describe(Envelope value) => value.Items is null ? "null" : $"[{string.Join(",", value.Items)}]";

/// <summary>Defines a concrete XML array contract with distinct empty and nil states.</summary>
public sealed class Envelope {
	[AllowNull, MaybeNull]
	[XmlArray("Items", IsNullable = true)]
	[XmlArrayItem("Item")]
	public string[] Items { get; set; } = Array.Empty<string>();
}

Expected output:

Plain text
Round-trip null: nil -> null
Round-trip []: 0 item(s) -> []
Round-trip [bolt,nut]: 2 item(s) -> [bolt,nut]
Missing element: []
Empty element: []
Nil element: null

The sample inspects the serialized XML structurally instead of comparing whitespace, an XML declaration or namespace prefix choices. The xsi prefix is conventional, while the namespace URI and nil local name identify the attribute. AllowNull and MaybeNull describe the property's null contract to the C# compiler. The separate XML attributes control serialization.

Make the XML states intentional

[XmlArray(IsNullable = true)] lets a null array produce an element with xsi:nil="true". A non-null zero-length array produces an empty wrapper. With IsNullable = false, null instead omits that wrapper during serialization. It does not promise to convert null into an empty array. These behaviors are documented by XmlArrayAttribute.IsNullable .

For this DTO, a missing element leaves the initialized empty array in place. An explicit nil value overwrites that initial value with null. The constructor or initializer runs before the serializer applies values, so initialization alone is not a rule that forbids null throughout deserialization.

If the application treats null and empty identically, normalize at the boundary after deserialization with envelope.Items ??= Array.Empty<string>(). If they have different meanings, preserve both. Do not silently erase a distinction required by an external schema or an update protocol where missing may mean “leave unchanged”.

Separate sequence APIs from transport data

An IEnumerable<string> property could represent a generator, query, array or collection with no usable construction path. An interface-typed property is not a universal XmlSerializer collection contract. The serializer supports particular public shapes and collection patterns, not arbitrary implementation choices behind an interface. See the XmlSerializer requirements .

Materialize the intended values into the transport array, for example dto.Items = source.ToArray(), before serialization. That enumeration can execute deferred work and can fail, so place it where the application can handle those outcomes. For a large or unbounded source, reconsider the protocol rather than materializing it accidentally.

If an existing public model cannot change, an [XmlIgnore] sequence member and a concrete serialized surrogate are another option. Define how the two stay consistent and avoid repeated enumeration or hidden side effects in property getters. A separate DTO often keeps that responsibility clearer.

Test the contract at the boundary

Retain cases for missing, nil, empty, one item and multiple items. Add cases for unexpected elements and namespaces when another system owns the schema. The example covers the collection wrapper, not nullable individual items or polymorphic item types. Those need their own attributes and tests.

XmlSerializer is a serialization mechanism rather than a substitute for schema validation or an input-security policy. This example reads only fixed local strings. When accepting untrusted XML, choose explicit reader settings and resource limits at the input boundary. Also verify trimming or Native AOT constraints separately before deploying a reflection-based serializer into such a build.

Source and further reading

This article revisits the problem raised in the following original posts. The explanation and examples here are newly written for .NET 10. A linked question supplies the motivation, rather than an author-attributed solution.

XmlSerializer Class (System.Xml.Serialization)
Serializes and deserializes objects into and from XML documents. The XmlSerializer enables you to control how objects are encoded into XML.
https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer?view=net-10.0
XmlArrayAttribute.IsNullable Property (System.Xml.Serialization)
Gets or sets a value that indicates whether the XmlSerializer must serialize a member as an empty XML tag with the xsi:nil attribute set to true.
https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlarrayattribute.isnullable?view=net-10.0
Attributes That Control XML Serialization - .NET
This article contains attributes you can apply to classes and class members to control how the XmlSerializer serializes or deserializes an instance of a class.
https://learn.microsoft.com/en-us/dotnet/standard/serialization/attributes-that-control-xml-serialization

Author: Herman Schoenfeld