среда, 3 ноября 2010 г.

Why do I have to XmlInclude derived classes in order to serialize?

I have a shallow, but wide class heirarchy.  I have one base class with several derived classes.
During serialization, I pass a reference to the XmlSerializer.  The reference never points to the base class; it points to one of the derived classes.

So when I attempt to serialize

public class Base

public class Derived1 : Base
public class Derived2 : Base
public class DerivedN : Base


XmlSerializer ser = new XmlSerializer(typeof(Base));
StreamWriter writer = new StreamWriter(sFilename);
ser.Serialize(writer, DerivedClassFactory.CreateRandom() );
//DerivedClassFactory can create any of the derived classes..



On this last line, the execution fails with a run time error:
"The type LibraryName.Classname was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

I took this suggestion and added
    [System.Xml.Serialization.XmlInclude(typeof(Derived1))]
    [System.Xml.Serialization.XmlInclude(typeof(Derived2))]
    [System.Xml.Serialization.XmlInclude(typeof(DerivedN))]

to the Base class definition.  The code now executes fine.  The problem is, what if I do not own the base class definition?  What if I do not have access to the base class definition?  Isn't there a better way to do this????




You can achieve the same by using different XmlSerializer ctor, the one that takes an univerce of “known” types:   public XmlSerializer(Type type, Type[] extraTypes){..}

In your case: new XmlSerializer(typeof(Base), new Type[] { typeof(Derived1), ..});

Комментариев нет: