Using IXmlSerializable To Overcome “not expected” Error On Derived Classes
This article extends upon Simon Hewitt’s article on CodeProject. It is strongly recommended that you read Simon’s article also in order to fully understand the concepts.
BACKGROUND
XML serialization is an indispensable technique that has built-in support for in the .NET Framework. Using XML serialization, objects can be serialized to XML streams that may be persisted to permanent storage such as files, as well as XML streams can be converted back to objects with exactly the same state as at the time of serialization. With .NET Framework’s built-in support for XML serialization, all this can be achieved with only a few lines of code using the System.Xml.Serialization.XmlSerializer object.
PROBLEM
The problem with XmlSerializer is, however, that it works by generating an on-the-fly assembly behind the scenes at compilation time, that has logic for serialization and deserialization of a given type. For this reason, the exact (concrete) type of the object and it’s public properties must be known to the compiler at the time of compilation. If we try to serialize an object that, for example, has a public member of a given base type, then at run-time we receive a System.InvalidOperationException if the public member was set to a derived type.
WORKAROUND
The workaround to above problem has generally been resorting to custom XML serialization, which can get pretty complicated at times.
SOLUTION
An ingenious solutions was discovered by Simon Hewitt using the System.Xml.Serialization.IXmlSerializable interface that allows us to mitigate the by-design issue of XmlSerializer object. While this solution works very well, it requires that a new class be created for each base class that we need serialization support for.
Using C# generics, I took the liberty of extending Simon’s solution, eliminating the need for such new classes, and encapsulating the grunt work into just one class. Once this class has been added to our project (our referenced from another assembly), all we really need to do is decorate any of our public members of base type (that may be substituted with derived types at runtime) with an attribute.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Vocalsoft.Xml.Serialization
{
public class CustomSerializer : IXmlSerializable
{
#region Private Members
///
/// Holds the object that this serializer operates on.
///
private ItemType _parameters;
#endregion
#region Static Methods
///
/// Implicit operators the specified p.
///
/// The p.
///
public static implicit operator
CustomSerializer(ItemType p)
{
return p == null ? null : new CustomSerializer(p);
}
///
/// Implicit operators the specified p.
///
/// The p.
///
public static implicit operator
ItemType(CustomSerializer p)
{
return p.Equals(default(ItemType)) ? default(ItemType) : p.Parameters;
}
#endregion Static
#region Constructors
///
/// Initializes a new instance of the "/> class.
///
public CustomSerializer()
{
}
///
/// Initializes a new instance of the "/> class.
///
/// The parameters.
public CustomSerializer(ItemType parameters)
{
this._parameters = parameters;
}
#endregion Constructors
#region Properties
///
/// Gets parameters.
///
/// The parameters.
public ItemType Parameters
{
get { return _parameters; }
}
#endregion Properties
#region IXmlSerializable Implementation
///
/// Returns schema of the XML document representation of the object that is produced by the method and consumed by the method.
///
///
/// An that describes the XML representation of the object that is produced by the method and consumed by the method.
///
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
///
/// Generates an object from its XML representation.
///
/// The stream from which the object is deserialized.
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Get type from xml attribute
Type type = Type.GetType(reader.GetAttribute("type"));
// Deserialize
reader.ReadStartElement();
this._parameters = (ItemType)new XmlSerializer(type).Deserialize(reader);
reader.ReadEndElement();
}
///
/// Converts an object into its XML representation.
///
/// The stream to which the object is serialized.
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Write type as xml attribute
writer.WriteAttributeString("type", _parameters.GetType().ToString());
new XmlSerializer(_parameters.GetType()).Serialize(writer, _parameters);
}
#endregion IXmlSerializable Implementation
}
}
Once the above class has been added to our project, all we need to do is add an attribute directly on the base class property as follows:
[XmlElement(Type = typeof(CustomSerializer))]
