I got some issues with the XmlSerializer in .NET.
Here I have a small example I built up just right now. (also available @ gist https://gist.github.com/2d84be9041a3f9c06237)
using System.IO;
using System.Xml.Serialization;
namespace XmlSerializingSample
{
internal class Program
{
private static void Main(string[] args)
{
var specialType = new SpecialType()
{
Id = 1,
Name = "test"
};
var serializer = new XmlSerializer(typeof (SpecialType));
var des = new XmlSerializer(typeof (BaseType));
using (var memeStream = new MemoryStream())
{
serializer.Serialize(memeStream, specialType);
memeStream.Flush();
memeStream.Seek(0, SeekOrigin.Begin);
var instance = des.Deserialize(memeStream); // Here it throws the exception
}
}
}
[XmlInclude(typeof(SpecialType))]
[XmlType("baseType")]
public class BaseType
{
public long Id { get; set; }
}
[XmlRoot("special")]
public class SpecialType : BaseType
{
public string Name { get; set; }
}
}
In line 24 of the code I get an InvalidOperationException stating “{“<special xmlns=”> wurde nicht erwartet.”}” [yes, it’s german]
All Posts I found stated, after adding XmlIncludeAttribute on the base type being deserialized, this should work. Did I forget sth.?
Regards,
MacX
The problem is that your Serializer is serializing the SpecialType with a root element as so:
But then you try to Deserialize it using
var des = new XmlSerializer(typeof (BaseType));it knows about both types but it doesn’t know how to handle therootelement in the xml.If you want this to work, you need to also set the root element of the base type to serialize as
special. In other words, you would need to do this:That way, the deserializer knows how to handle
specialas the root element.I don’t think there are other simple alternatives to make this work out of the box.
Update
This is another alternative using the XmlAttributeOverrides class.
LinqPad code: