Skip to main content
This article shows how to serialize an object graph in which the same object appears more than once. By default, XmlSerializer writes an object every time it meets it, so a shared object becomes two copies and a cycle never ends. A reference handler changes that. The API mirrors System.Text.Json: set XmlSerializerOptions.ReferenceHandler to XmlReferenceHandler.Preserve or XmlReferenceHandler.IgnoreCycles, as you would set JsonSerializerOptions.ReferenceHandler. The markup is different, because XML has attributes and namespaces where JSON has $id and $ref properties.
The examples on this page use the reflection-based serializer. A source-generated context handles references in the same way when its options have a ReferenceHandler. See Source generation.

See what happens without a handler

The examples on this page use an Employee type that points to its manager and to its direct reports, so a manager and a report refer to each other.
Employee.cs
With no reference handler, the serializer follows the cycle until the writer reaches its depth limit:
Program.cs
The code produces the following output:
The limit is XmlSerializerOptions.MaxDepth, which is 64 unless you change it. The serializer doesn’t detect the cycle itself. It stops because the document became too deep. View the complete sample on GitHub

Preserve references

Set ReferenceHandler to XmlReferenceHandler.Preserve to keep object identity. The serializer gives each object an identifier the first time it writes it. When a member holds an object that was already written, the serializer writes a reference to that identifier instead of the object.
Program.cs
The code produces the following output:
The last line shows that the cycle is restored: the report’s manager is the same instance as the root.

What the markup looks like

  • The built-in identifiers are the numbers 1, 2, 3, and so on, in the order the objects are written. Numbering starts again for every call to Serialize.
  • The writer generates the prefix. When the serializer reads, only the namespace URI matters, so a document can bind the namespace to any prefix.
  • The attributes are in a namespace of their own so that they can’t collide with an id or ref attribute that belongs to your type.
  • Only objects with members get an identifier. Strings, numbers, other simple values, and the collections themselves do not.

Keep one object as one object

A cycle is the case that fails loudly. A shared object fails quietly: without a handler it is written twice and read back as two objects. With Preserve, it stays one object.
Program.cs
Project.cs
The code produces the following output:
View the complete sample on GitHub

Rules for reading

  • Use options with the same handler to read the document. Without a handler, an id attribute is ignored and a ref attribute is an XmlException.
  • A ref must point to an id that appears earlier in the document. A reference to an unknown identifier is an XmlException with the message Unknown reference '...'.
  • An element with a ref attribute is replaced by the referenced object. Any content it has is skipped.
  • An object that is created through a constructor with parameters is registered under its identifier after the constructor runs. A document can refer to it later, but the object can’t hold a reference to itself: reading one that does throws an XmlException whose message starts with Unknown reference '1'.

Where Preserve applies

Preserve replaces a repeated object wherever it appears: as the value of a member, as an item of a collection, and as an item inside a wrapper element. If the same object is in a list twice, the second item is written as an empty element with a ref attribute, and the list reads back as one object held twice. Value types and the collections themselves have no identifier. A list that two members share is written in full each time, and its items are still written once.

Ignore cycles

XmlReferenceHandler.IgnoreCycles writes no identifiers. When the serializer reaches an object from inside that same object, it writes nil in its place and goes no deeper.
Program.cs
The code produces the following output:
The document is plain XML that any consumer can read, and it is no longer the same graph: the report’s Manager is null after a round trip. Only a cycle is written as nil. An object that two members share, or that is in a list twice, is written in full each time, as System.Text.Json writes it. In the Project example above, Owner and Reviewer would both hold the whole employee, and the document would read back as two separate objects. To keep them as one object, use Preserve. View the complete sample on GitHub

Choose a handler

Use a custom resolver

To control how identifiers are resolved, derive from XmlReferenceHandler and XmlReferenceResolver, as you would derive from ReferenceHandler and ReferenceResolver in System.Text.Json. The serializer calls CreateResolver once for each call to Serialize or Deserialize. The following handler keeps every identified object in a dictionary, so that the caller can look objects up by identifier after the document has been read.
Program.cs
Program.cs
The code produces the following output:
The first three lines show the custom resolver at work while reading: identifiers don’t have to be numbers, and the handler’s dictionary holds both objects afterward. The last line shows it at work while writing: the serializer writes the identifiers that GetReference returns as id attributes, and writes ref for an object the resolver says it has already seen.
If GetReference returns an empty string, the serializer writes no id. For an object that the resolver reports as already seen, an empty string makes the serializer write nil in its place.
A resolver holds state for one call. If your handler shares state between calls, as this one does, don’t use the same options for calls that run at the same time. View the complete sample on GitHub

Understand the cost

A reference handler makes the serializer look up every object it writes. Writing with Preserve takes noticeably longer than writing with no handler. The cost is a dictionary lookup, an identifier string, and a namespaced attribute for each object. Leave ReferenceHandler unset, which is the default, unless the graph needs it. With no handler, the serializer does no reference tracking at all.

See also

Null and nil

How xsi:nil is written and read.

Configure options

Create and reuse XmlSerializerOptions.

Use XML namespaces

How the serializer declares and matches namespaces.

XmlReferenceHandler

API reference for the handler.