Definition
Assembly: CloudNimble.XmlEssentials.dll Namespace: CloudNimble.Text.Xml.Serialization Inheritance: CloudNimble.Text.Xml.Serialization.XmlConverterSyntax
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 fromXmlConverter<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.
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 registersMoneyConverter 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.
Convert a built-in type in elements, attributes, and text
Best Practices
- Check
IsEmptyElementfirst inRead. An empty-element tag has no end-tag token. A loop that reads untilEndElementwithout 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
refto helper methods.Utf8XmlReaderis 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
XmlExceptionfor 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
CanConverton anXmlConverter<T>. A converter can serve onlyT. Use anXmlConverterFactoryfor 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
HandleNullat its default offalse, the serializer handles an element markedxsi:nil="true"itself: it returnsnullwithout callingRead, or throwsXmlExceptionwhenTcan’t benull. OverrideHandleNullto returntrueto receive those elements. - Attributes and text need more overrides.
ReadAsAttribute,WriteAsAttribute, andReadLexicalthrowInvalidOperationExceptionunless 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
Metadatamode uses your converter as the reflection resolver does, whether it’s inXmlSerializerOptions.Convertersor 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
Readonce. A converter never has to resume part way through an element. - Differences from
JsonConverter<T>.ReadandWritework on an element, not on a token. There are noReadAsPropertyNameorWriteAsPropertyNamemethods.HandleNullconcernsxsi:nilwhen reading.
Constructors
.ctor Inherited
Inherited from
CloudNimble.Text.Xml.Serialization.XmlConverterXmlConverter1` and XmlConverterFactory.
Syntax
.ctor Inherited
Inherited from
objectSyntax
Properties
CanPopulate Inherited Virtual
Inherited from
CloudNimble.Text.Xml.Serialization.XmlConverterSyntax
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 markedxsi: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 isfalse, 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.XmlConverterSyntax
Property Value
Type:bool
Methods
CanConvert Override
Syntax
Parameters
Returns
Type:bool
CanConvert Inherited Abstract
Inherited from
CloudNimble.Text.Xml.Serialization.XmlConverterSyntax
Parameters
Returns
Type:bool
true if the instance can convert typeToConvert; otherwise, false.
CreateTypeInfo Inherited Abstract
Inherited from
CloudNimble.Text.Xml.Serialization.XmlConverterSyntax
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
objectSyntax
Parameters
Returns
Type:bool
Equals Inherited
Inherited from
objectSyntax
Parameters
Returns
Type:bool
GetHashCode Inherited Virtual
Inherited from
objectSyntax
Returns
Type:int
GetType Inherited
Inherited from
objectSyntax
Returns
Type:System.Type
MemberwiseClone Inherited
Inherited from
objectSyntax
Returns
Type:object
Populate Inherited Virtual
Inherited from
CloudNimble.Text.Xml.Serialization.XmlConverterSyntax
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
objectSyntax
Parameters
Returns
Type:bool
Resolve Inherited Abstract
Inherited from
CloudNimble.Text.Xml.Serialization.XmlConverterSyntax
Parameters
Returns
Type:CloudNimble.Text.Xml.Serialization.XmlConverter
The converter.
ToString Inherited Virtual
Inherited from
objectSyntax
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.Related APIs
- 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