开发者

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 u开发者_Go百科nderstanding 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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜