Problem with IXmlSerializable, inheritance, and xsi:type

B

burningmidget

I am having trouble using IXmlSerializable within a base class and
having xsi:type work correctly when deserializing an xml file. Here is
a very simplified version of the what is going on in the code:

public class BaseJunkClass : IXmlSerializable
{
public void ReadXml(XmlReader Reader) { }

public void WriteXml(XmlWriter Writer) { }

public XmlSchema GetSchema()
{
return null;
}
}

public class DerivedJunkClass : BaseJunkClass
{
}

public class JunkClassContainer
{
public BaseJunkClass JunkClass;
}

And here is the code to deserialize this:

Type[] JunkTypes = new Type[] { typeof(BaseJunkClass),
typeof(DerivedJunkClass) };

XmlSerializer JunkSerializer = new
XmlSerializer(typeof(JunkClassContainer), JunkTypes);

FileStream JunkStream = new FileStream("JunkConfiguration.xml",
FileMode.Open, FileAccess.Read);

JunkClassContainer TestSerialization =
(JunkClassContainer)JunkSerializer.Deserialize(JunkStream);

And here are the xml file contents:

<?xml version="1.0" encoding="utf-8" ?>
<JunkClassContainer xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance">

<JunkClass xsi:type="DerivedJunkClass"></JunkClass>

</JunkClassContainer>

After running this code, TestSerialization contains an instance of
type BaseJunkClass, instead of DerivedJunkClass. What's more strange,
is that when this same code runs on the compact framework, it works as
desired. That is, in the compact framework TestSerialization contains
an instance of type DerivedJunkClass.

I came up with a dirty solution to fix this, but I was wondering if
there was a cleaner way. Maybe I'm missing a SerializableAttribute
somewhere, or something additional in the xml file? Any thought or
suggestions would be appreciated.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top