Class DynamicXmlSerializable
- Namespace
- Cuemon.Xml.Serialization
- Assembly
- Cuemon.Xml.dll
Provides a factory based way to create and wrap an IXmlSerializable implementation.
public static class DynamicXmlSerializable
- Inheritance
-
DynamicXmlSerializable
Examples
The following example wraps an anonymous object with DynamicXmlSerializable and provides a custom writer that emits Name and Score child elements. The resulting XML is written to a StringWriter and printed to the console.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Cuemon.Xml.Serialization;
namespace Cuemon.Xml.Serialization;
public class DynamicXmlSerializableExample
{
public void Demonstrate()
{
var data = new { Name = "Alice", Score = 95 };
var serializable = DynamicXmlSerializable.Create(data,
writer: (w, src) =>
{
w.WriteElementString("Name", src.Name);
w.WriteElementString("Score", src.Score.ToString());
});
using var sw = new StringWriter();
using var writer = XmlWriter.Create(sw);
serializable.WriteXml(writer);
writer.Flush();
Console.WriteLine(sw.ToString());
}
}
Methods
Create<T>(T, Action<XmlWriter, T>, Action<XmlReader>, Func<XmlSchema>)
Creates a dynamic instance of an IXmlSerializable implementation wrapping WriteXml(XmlWriter) through writer, ReadXml(XmlReader) through reader and GetSchema() through schema.
public static IXmlSerializable Create<T>(T source, Action<XmlWriter, T> writer, Action<XmlReader> reader = null, Func<XmlSchema> schema = null)
Parameters
sourceTThe object that needs support for an IXmlSerializable implementation.
writerAction<XmlWriter, T>The delegate that converts
sourceto its XML representation.readerAction<XmlReader>The delegate that generates
sourcefrom its XML representation.schemaFunc<XmlSchema>The function delegate that can provide a schema of the
source.
Returns
- IXmlSerializable
An IXmlSerializable implementation of
source.
Type Parameters
TThe type of the
sourceto implement an IXmlSerializable.