Skip to main content

Definition

Assembly: CloudNimble.XmlEssentials.dll Namespace: CloudNimble.Text.Xml.Serialization Inheritance: CloudNimble.Text.Xml.Serialization.XmlConverter

Syntax

Summary

Converts an object or value to or from XML.

Usage

A converter reads one type from XML and writes it back. To write your own, derive from XmlConverter<T> and override Read and Write. You can’t derive from the non-generic XmlConverter class directly: it’s the common base of XmlConverter<T> and XmlConverterFactory.
Register the converter by adding an instance to XmlSerializerOptions.Converters, or by naming it in [XmlConverter] on the type it converts.

Where Read starts and stops

Read is called with the reader on the start tag of the element that holds the value. It must leave the reader on the last token of that element: the end tag, or the start tag itself when the element is an empty-element tag such as <Total/>, which has no end-tag token. Check reader.IsEmptyElement before the first call to reader.Read().

What Write writes

Write is called after the serializer has written the element’s start tag. Write the content, text or child elements, and return. The serializer writes the end tag. The classes correspond to JsonConverter and JsonConverter<T> in System.Text.Json. For the factory pattern, registration, and attribute support, see How to write custom converters.

Remarks

XmlConverter`1.Read is called with the reader positioned on the start tag of the value. The converter consumes through the matching end tag, or handles an empty element.

Type Parameters

  • T - The type of object or value handled by the converter.

Examples

Register converters in the options

The following example registers MoneyConverter and a second converter that replaces the built-in converter of DateOnly. Issued is mapped as an attribute, so it’s written by the date converter’s WriteAsAttribute method.
The code produces the following output:

Convert a built-in type in elements, attributes, and text

View the complete sample on GitHub

Best Practices

  • Check IsEmptyElement first in Read. An empty-element tag has no end-tag token. A loop that reads until EndElement without the check runs into the elements that follow.
  • Leave the reader on the element’s last token. Don’t read past the end tag, and don’t stop before it. The serializer continues from where you stop.
  • Pass the reader by ref to helper methods. Utf8XmlReader is a struct. A helper that takes it by value advances a copy.
  • Skip what you don’t recognize. Call reader.Skip() on an unknown child element so that a newer document doesn’t break an older converter.
  • Close every element you open in Write, and don’t write the value’s own start or end tag.
  • Throw XmlException for content that isn’t valid, as the built-in converters do.
  • Format and parse with CultureInfo.InvariantCulture. XML is exchanged between machines, and the current culture changes decimal separators and date order.
  • Keep converters stateless. One instance serves every thread that uses the options.
  • Don’t widen CanConvert on an XmlConverter<T>. A converter can serve only T. Use an XmlConverterFactory for a family of types.

Considerations

  • Lookup order. The serializer uses the first match among the converters in XmlSerializerOptions.Converters, in list order, then [XmlConverter] on the type, then the built-in converters.
  • Nil elements. With HandleNull at its default of false, the serializer handles an element marked xsi:nil="true" itself: it returns null without calling Read, or throws XmlException when T can’t be null. Override HandleNull to return true to receive those elements.
  • Attributes and text need more overrides. ReadAsAttribute, WriteAsAttribute, and ReadLexical throw InvalidOperationException unless you override them. The serializer calls them only for the types it treats as simple values, such as numbers, dates, strings, and enumerations, when a member is mapped with [XmlAttribute], [XmlText], or [XmlCData]. A member of any other type can’t be an attribute or text, whatever its converter writes.
  • Source generation. A source-generated context in the default mode or in Metadata mode uses your converter as the reflection resolver does, whether it’s in XmlSerializerOptions.Converters or named by [XmlConverter] on a type or a member. A converter you supply for a type is used in place of the generated metadata for that type. See Use a converter with source generation.
  • Stream reads. When the serializer reads from a stream and the document isn’t all in memory yet, it first makes sure the whole element has arrived and then calls Read once. A converter never has to resume part way through an element.
  • Differences from JsonConverter<T>. Read and Write work on an element, not on a token. There are no ReadAsPropertyName or WriteAsPropertyName methods. HandleNull concerns xsi:nil when reading.

Constructors

.ctor Inherited

Inherited from CloudNimble.Text.Xml.Serialization.XmlConverter
Limits derivation to XmlConverter1` and XmlConverterFactory.

Syntax

.ctor Inherited

Inherited from object

Syntax

Properties

CanPopulate Inherited Virtual

Inherited from CloudNimble.Text.Xml.Serialization.XmlConverter
Gets whether the converter can read an element into a value that already exists.

Syntax

Property Value

Type: bool true for the converters of objects and dictionaries that the library creates; otherwise, false. A converter the caller wrote creates its value, so a member it reads is replaced.

HandleNull Virtual

Gets a value that indicates whether an element marked xsi:nil="true" is passed to the converter on deserialization.

Syntax

Property Value

Type: bool true if XmlConverter1.Read](/xmlessentials/api-reference/CloudNimble/Text/Xml/Serialization/XmlConverter#read) is called for an element marked xsi:nil=“true”; otherwise, [false](https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/bool). The default is [false`.

Remarks

When the value is false, the serializer returns null for a nil element without calling XmlConverter1.Read](/xmlessentials/api-reference/CloudNimble/Text/Xml/Serialization/XmlConverter#read), and throws an [XmlException](/xmlessentials/api-reference/CloudNimble/Text/Xml/XmlException) when *T* is a value type that cannot be [null`.

IsValueConverter Inherited Virtual

Inherited from CloudNimble.Text.Xml.Serialization.XmlConverter
Gets whether this is one of the built-in converters that read and write a value from its lexical form, which the serializer can call directly.

Syntax

Property Value

Type: bool

Methods

CanConvert Override

Syntax

Parameters

Returns

Type: bool

CanConvert Inherited Abstract

Inherited from CloudNimble.Text.Xml.Serialization.XmlConverter
When overridden in a derived class, determines whether the converter instance can convert the specified type.

Syntax

Parameters

Returns

Type: bool true if the instance can convert typeToConvert; otherwise, false.

CreateTypeInfo Inherited Abstract

Inherited from CloudNimble.Text.Xml.Serialization.XmlConverter
Creates type info that reads and writes typeToConvert with this converter.

Syntax

Parameters

Returns

Type: CloudNimble.Text.Xml.Serialization.XmlTypeInfo? The type info, or null when this converter cannot produce values of that exact type.

Equals Inherited Virtual

Inherited from object

Syntax

Parameters

Returns

Type: bool

Equals Inherited

Inherited from object

Syntax

Parameters

Returns

Type: bool

GetHashCode Inherited Virtual

Inherited from object

Syntax

Returns

Type: int

GetType Inherited

Inherited from object

Syntax

Returns

Type: System.Type

MemberwiseClone Inherited

Inherited from object

Syntax

Returns

Type: object

Populate Inherited Virtual

Inherited from CloudNimble.Text.Xml.Serialization.XmlConverter
Reads the element reader is on into existing.

Syntax

Parameters

Exceptions

Read Abstract

When overridden in a derived class, reads and converts the XML element to type T.

Syntax

Parameters

Returns

Type: T? The converted value.

ReadAsAttribute Virtual

Reads and converts the value of the current XML attribute to type T.

Syntax

Parameters

Returns

Type: T? The converted value.

Exceptions

Remarks

The default implementation throws an InvalidOperationException. Override this method in a converter whose type can be mapped to an XML attribute.

ReadLexical Virtual

Converts the lexical form of a value, as decoded UTF-8 text content, to type T.

Syntax

Parameters

Returns

Type: T? The converted value.

Exceptions

Remarks

The default implementation throws an InvalidOperationException. Override this method in a converter whose type can be read from simple content.

ReferenceEquals Inherited

Inherited from object

Syntax

Parameters

Returns

Type: bool

Resolve Inherited Abstract

Inherited from CloudNimble.Text.Xml.Serialization.XmlConverter
Returns the converter that does the work for typeToConvert: this converter, or the one a factory creates.

Syntax

Parameters

Returns

Type: CloudNimble.Text.Xml.Serialization.XmlConverter The converter.

ToString Inherited Virtual

Inherited from object

Syntax

Returns

Type: string?

Write Abstract

When overridden in a derived class, writes the specified value as the content of the current XML element.

Syntax

Parameters

WriteAsAttribute Virtual

Writes the specified value as an XML attribute with the specified name.

Syntax

Parameters

Exceptions

Remarks

The default implementation throws an InvalidOperationException. Override this method in a converter whose type can be mapped to an XML attribute.
  • CloudNimble.Text.Xml.Serialization.XmlConverterFactory
  • CloudNimble.Text.Xml.Serialization.XmlConverterAttribute
  • CloudNimble.Text.Xml.Serialization.XmlTypeInfo
  • CloudNimble.Text.Xml.XmlSerializerOptions
  • CloudNimble.Text.Xml.Utf8XmlReader
  • CloudNimble.Text.Xml.Utf8XmlWriter
  • CloudNimble.Text.Xml.XmlException
  • CloudNimble.Text.Xml.XmlName