IXmlSerializable and Derived Classes


Julian Mensch

I've recently run into a complication with XML serialization
using the .NET Framework (2.0). Prior to this issue I had a
fairly simple serialization setup -- all my data classes inherit
from a base class which has methods to use a standard
XmlSerializer object to convert any data class to XML and
back, as well as any classes it might have references to.

The approach is simple -- just create an XmlSerializer with
typeof(BaseClass) as the first parameter, and an array of
Type objects for all different derived classes as the second
parameter. (It's fairly easy to get this, and then cache it, as
a one-time operation with .NET reflection.)

This works great when you control serialization using the
simple methods (i.e., XmlIgnore, *Specified members, etc.)
However, I've discovered I need a more precise programmatic
method of controlling which members get serialized and how,
so I decide to implement the IXmlSerializable interface on the
base class. For this, too, I used reflection -- so the base
class implementation of XmlWrite() works fine for all the derived
classes, iterating through their properties using reflection and
serializing each.

Now the problem. The _serialization_ works great, but when
I try to _deserialize_, the XmlSerializer builds an object of the
base class rather than whatever derived class I'm trying to
deserialize from XML. (Then the XmlRead throws exceptions
because it can't find the expected properties with reflection.)

I have added the following line to XmlWrite() to get it to write
object type information to the generated XML in the same form
as it was written when I wasn't using IXmlSerializable:


However, this does not solve the problem -- the object created
is still of the BaseClass type. Then I tried changing the type of
the first parameter to XmlSerializer to typeof(DerivedClass), and it
STILL created a BaseClass object instead! (That wouldn't be a
solution anyway, since I need my serialization to be generic and
not tied to specific classes.)

Can anyone explain to me how I can get XmlSerializer to instantiate
the _correct_ class type when using IXmlSerializable?

Thanks for any help anyone can offer,

-- Julian Mensch


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