[XmlPolymorphic] and [XmlDerivedType<T>] play the roles of [JsonPolymorphic] and [JsonDerivedType]. The difference is where the type name goes. JSON needs a $type property. XML already has a place for it: the name of the element.
The examples on this page use the reflection-based serializer. A source-generated context reads and writes derived types in the same way. List the base type on the context, and the generator includes the derived types that
[XmlDerivedType<T>] names. See Source generation.Serialize the declared type only
Without any attributes, the serializer writes the members of the declared type and nothing else. A derived class that isn’t declared is not written by accident. This is the same default as System.Text.Json, and it prevents a derived type from exposing data that the contract never mentioned.Declare the derived types
To opt in, put one[XmlDerivedType<T>] on the base type for each derived type. [XmlPolymorphic] is optional: add it to choose another placement for the discriminator, the name of a discriminator attribute, the handling of an undeclared type, or closed-type inference. By default, each derived type is written under an element named after it. Pass a string to choose another name.
Product.cs
Program.cs
- The element name is the discriminator.
<Book>becomes aBookand<Disc>becomes aDvd, with every member of the derived type. - An object of the base type itself is written under the member’s own name,
<Products>, and is read back as aProduct. - An element named for a derived type is matched the way every element name is: exactly, or without regard to the case of ASCII letters when
PropertyNameCaseInsensitiveistrue. - The naming policy for elements applies to a discriminator that is used as an element name. With
PropertyNamingPolicy = XmlNamingPolicy.CamelCase,Bookis written as<book>.ElementNamingPolicytakes precedence when it is set. - A derived type’s element can be in a namespace of its own. Set
Namespaceon the attribute: with[XmlDerivedType<Invoice>(Namespace = "urn:billing")], anInvoiceis written as<Invoice xmlns="urn:billing">, and only anInvoiceelement in that namespace is read as one. - A discriminator can’t be the element name of another member of the containing type. If two members could claim the same element name, the serializer throws an
InvalidOperationExceptionwhen it first builds the type’s metadata. Give each derived type its own discriminator.
[XmlDerivedType<T>] is a generic attribute, so the derived type is checked by the compiler. The discriminator is always a string. There is no integer form.
The declared base type can be a concrete class, an abstract class, or an interface. An abstract class or an interface must list its derived types with [XmlDerivedType<T>], because the serializer can’t create the declared type itself:
- When reading, an element that doesn’t identify a derived type throws
XmlExceptionwith a message that names the base type:The type 'Vehicle' is abstract or an interface, so the element must identify one of its derived types. Path: /Garage/Main | LineNumber: 1 | BytePositionInLine: 16.A concrete base class would be created instead. - When writing, a value whose type isn’t listed throws
NotSupportedException, unless the base type setsUnknownDerivedTypeHandling. - An abstract class or an interface with no
[XmlDerivedType<T>]isn’t supported, and the serializer throwsNotSupportedExceptionwith the messageThe type '...' is not supported.
Choose where the discriminator is written
SetXmlPolymorphicAttribute.DiscriminatorPlacement to one of the XmlDiscriminatorPlacement values.
Use an attribute when the element name must stay the same for every derived type, for example because a schema fixes it.
Use an attribute
WithXmlDiscriminatorPlacement.Attribute, TypeDiscriminatorPropertyName is required. The string you pass to [XmlDerivedType<T>] is the attribute’s value.
Payment.cs
Program.cs
XmlException. An element with no discriminator attribute at all is read as the declared type.
The discriminator attribute can appear anywhere in the start tag. Unlike a JSON $type property, it never has to come first, because the serializer sees every attribute of an element before it reads the element’s content.
View the complete sample on GitHub
Use xsi:type
XmlDiscriminatorPlacement.XsiType writes the discriminator as xsi:type, the attribute that XML Schema defines for this purpose and that System.Xml.Serialization.XmlSerializer also writes. The value is the discriminator string exactly as you declared it, with no namespace prefix. When reading, the exact string is tried first; a value with a prefix, such as p:Truck, is then matched by the part after the colon, whatever namespace the prefix is bound to. The next example uses this placement.
Handle a type that isn’t declared
A runtime type that the base type doesn’t declare is rejected by default.Ebook derives from Book, but Product doesn’t list it:
Program.cs
XmlPolymorphicAttribute.UnknownDerivedTypeHandling to one of the XmlUnknownDerivedTypeHandling values.
The following hierarchy uses
xsi:type and falls back to the nearest ancestor. SportsCar derives from Car and isn’t declared.
Vehicle.cs
Program.cs
SportsCar is written as a Car. Its TopSpeed isn’t written, and the document reads back as a Car. A fallback loses the members of the undeclared type, so choose it only when that loss is acceptable.
This example also shows a polymorphic document root: the variable is declared as Vehicle, so the root element is <Vehicle> and the attribute names the derived type.
With
XmlDiscriminatorPlacement.ElementName, an element whose name isn’t declared doesn’t reach the polymorphism logic at all. Inside an object, it is content that no member maps, and UnmappedMemberHandling decides whether it is skipped or rejected. At the document root, it is an XmlException because the root name doesn’t match.Name the elements on the member
[XmlDerivedType] goes on a base type, so it applies wherever that type is used, and it needs the types to be related. When the types aren’t related, or the names belong to one member only, put the names on the member: more than one [XmlElement<T>] makes the member a choice of elements, where each element name stands for a type.
Timeline.cs
Program.cs
[XmlArrayItem<T>].
- Each type can have one element name and each element name one type, because a value is written under the element of its type. Two elements for one type are refused when the type is first used, unless the member holds named values.
- Every type must be assignable to the member’s type, or to the item type of a collection.
- A value whose type has no element is refused with a
NotSupportedException, except a value of the member’s own type, which is written under the member’s name.
NotSupportedException. The first two are thrown when the type is first used, and the third when the value is written:
Also know the following:
- When the type of an element declares derived types with
xsi:typeor an attribute, they still apply inside that element: a value of one of them is written under the element of its base type, with its discriminator.
When two elements hold the same type
AHome and a Work element that both hold text can’t be told apart by the type of the value. Declare the member as XmlNamedValue, or as a collection of it, and each value says which element it is:
ContactCard.cs
Program.cs
NotSupportedException when it is written. A value that is null is written as an element marked xsi:nil="true".
View the complete sample on GitHub
Mind the type you serialize as
WithAttribute or XsiType placement, the serializer uses the type you declare, not the runtime type, to choose the document element. With ElementName placement the element name is the discriminator, so a derived value serialized as its base type gets the element of the derived type as its document element. The next example uses Attribute placement and serializes the same CardPayment three ways: as Payment, as its own type through type inference, and as its runtime type through the overload that takes a Type.
Program.cs
System.Xml.Serialization and System.Text.Json. A derived type still inherits the list of its base type: if a type derived from a listed type, say an AudioBook that derives from Book, is also listed on the base type, a value of it serialized as Book is written with its discriminator, and a plain Book is written with none. When reading into a member declared as a derived type, a discriminator attribute, an xsi:type, or an item of a wrapped collection that names a type that isn’t that type or below it throws an XmlException: The element identifies the type '...', which is not a '...'. Under ElementName, an element named for such a type is content that no member maps. Read a document with the same type argument that wrote it: a document written as Payment has a <Payment> root, and Deserialize<CardPayment> expects <CardPayment>.
View the complete sample on GitHub
XmlInclude is not for derived types
If you come fromSystem.Xml.Serialization, you know [XmlInclude(typeof(Book))] as the way to declare a known derived type. In XmlEssentials that job belongs to [XmlDerivedType<T>].
[XmlInclude] in this library is the counterpart of [JsonInclude]: it goes on a property or field that isn’t public, and opts that member in to serialization. It also makes the serializer use a set or init accessor that isn’t public when it reads a public property.
Account.cs
Program.cs
Infer the derived types of a closed type
A closed type is a class declared with theclosed modifier, which needs C# 15 and .NET 11. Every type that derives from it is in its own assembly, and the compiler lists them. Set InferClosedTypePolymorphism and the serializer takes the derived types from that list, so you don’t write an [XmlDerivedType<T>] for each one.
InferClosedTypePolymorphism in System.Text.Json:
- The discriminator of a derived type is its name. For a generic type that is the name without its type arguments. It is written where
DiscriminatorPlacementsays, as a declared discriminator is. The element naming policy applies when it is an element name; as an attribute orxsi:typevalue it is written as the type name. - A derived type that is closed itself can’t be created, so the types that derive from it are used in its place.
[XmlPolymorphic(InferClosedTypePolymorphism = true)]on a type infers for that type whatever the options say, andfalseturns it off for that type.- A type that declares a derived type with
[XmlDerivedType<T>]has nothing inferred. What it declares is the whole list. [XmlPolymorphic(InferClosedTypePolymorphism = true)]on a type that isn’t closed throws anInvalidOperationExceptionthe first time the type is used.- A closed type whose derived types aren’t inferred, and that declares none, isn’t supported:
XmlSerializerthrows aNotSupportedException.
What isn’t supported
- Members of type
object. A member declared asobjectis written as the type its value has, with no discriminator, so the document doesn’t say which type wrote it. It is read back as anXmlElement, which you can read as the type you expect withXmlSerializer.Deserialize<T>(element). SetUnknownTypeHandlingtoXmlUnknownTypeHandling.XmlNodeto read anXmlNodeyou can change instead. To get the derived type back when reading, declare the member as a base type with[XmlDerivedType]. - Configuring polymorphism at run time. The attributes are the only way to declare derived types. There is no contract-customization API for it.
See also
Serialize
The basics of writing objects as XML.
Collections
Wrap a list of derived types in a parent element.
Custom converters
Take over reading and writing for a type the attributes can’t describe.
XmlPolymorphicAttribute
API reference for the attribute.