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 anEmployee type that points to its manager and to its direct reports, so a manager and a report refer to each other.
Employee.cs
Program.cs
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
SetReferenceHandler 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
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
idorrefattribute 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. WithPreserve, it stays one object.
Program.cs
Project.cs
Rules for reading
- Use options with the same handler to read the document. Without a handler, an
idattribute is ignored and arefattribute is anXmlException. - A
refmust point to anidthat appears earlier in the document. A reference to an unknown identifier is anXmlExceptionwith the messageUnknown reference '...'. - An element with a
refattribute 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
XmlExceptionwhose message starts withUnknown 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
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 fromXmlReferenceHandler 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
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.Understand the cost
A reference handler makes the serializer look up every object it writes. Writing withPreserve 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.