XmlSerializer exception when deserializing derived class (<Derived xmlns=''> was not expected)

I am trying to serialize and deserialize a hierarchy of classes using XmlSerializer. The serialization works fine, but when I try to deserialize I get this exception:

System.InvalidOperationException: There is an error in XML document (2, 2). ---> System.InvalidOperationException: <Derived xmlns=''> was not expected.

This is the xml that I am trying to deserialize:

<?xml version="1.0"?>
<Derived xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BaseStr>Base</BaseStr>
  <DerivedStr>Derived</DerivedStr>
</Derived>

This is the code that I am using:

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

[XmlInclude(typeof(Derived))]
public abstract class Base 
{
    public string BaseStr { get; set; }
}

public class Derived : Base
{
    public string DerivedStr { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Derived));
            MemoryStream ms = new MemoryStream();
            serializer.Serialize(ms, new Derived() { DerivedStr = "Derived", BaseStr = "Base" });

            Console.WriteLine(Encoding.ASCII.GetChars(ms.ToArray()));

            ms.Position = 0;

            XmlSerializer deserializer = new XmlSerializer(typeof(Base));
            Base b = (Base)deserializer.Deserialize(ms);
            Console.WriteLine(b.GetType().Name);
        }
        catch(Exception ex)
        {
            Console.WriteLine();
            Console.WriteLine(ex.ToString());
        }
    }
}

Why does the deserialization not work? How can I get it to work?

Jon Skeet
people
quotationmark

You're creating an XmlSerializer which expects to deserialize just Base objects. It doesn't expect to see a <Derived> element. If you use

XmlSerializer deserializer = new XmlSerializer(typeof(Derived));

you don't get the exception. Alternatively, when you serialize the instance of Derived, you can use a serializer which will produce a <Base> element:

XmlSerializer serializer = new XmlSerializer(typeof(Base));

That will still deserialize to an instance of Derived, because the XML will include

xsi:type="Derived"

Basically your serializer and deserializer need to be constructed with the same type.

people

See more on this question at Stackoverflow