JMcCarty
JMcCarty

Reputation: 759

XMLSerialization problem with Derived types

I am currently having a problem with de-serialization from XML when using derived classes. The serialization works just fine, but doing the reverse results in an unexpected element exception.

Sample code:

public class Foo
{
   //Some Properties
}

public class Bar : Foo
{
    //more properties
}

public class Holder : IXmlSerializable
{
   public Foo SomeObject;

   public void WriteXML(XmlWriter writer)
   {
       var lizer = new XmlSerializer(SomeObject.GetType());
       lizer.Serialize(writer,SomeObject);
   }

   public void ReadXML(XmlReader reader)
   {
       reader.MoveToContent();
       reader.ReadStartElement();

       var lizer = new XmlSerializer(typeof(Foo), new Type[] { typeof(Bar) });

       SomeObject = (Foo)lizer.Deserialize(reader);
   }

If Holder.SomeObject is set to an instance of Bar the serialization works exactly as expected. However the de-serialization is throwing. It was my understanding that if I gave the XmlSerializer ctor all of the possible types that it should be pick the correct one.

Is this not the case or am i just missing something? Thanks

Upvotes: 0

Views: 357

Answers (1)

Fergus Bown
Fergus Bown

Reputation: 1696

You need to use the same constructor for the XmlSerializer when you serialize as when you are deserializing, i.e. your code would change to this:

public void WriteXML(XmlWriter writer)
{
    var lizer = new XmlSerializer(typeof(Foo), new Type[] { typeof(Bar) });
    lizer.Serialize(writer,SomeObject);
}

Upvotes: 1

Related Questions