Custom XML Serialization

I recently created an application that needed a fairly deep class hierarchy.  One class contained another class, which contained another, and so on.  I needed to find an easy way to serialize this object and store it in a database.  I found a post on Jeff Kirwan's blog that showed how to serialize an object to XML, which could then be placed into a database.  This seemed to be an easy solution to my problem....

Then I got into trouble.  I needed to store the class data in relational form in the database, so that some of this data could be referenced by other stored procedures.  (The class hierarchy actually represents configuration data for an application.)  This is easy to do with SQL via OPENXML.  (See my Memphis .NET User's Group presentation.)  However, pulling this data out of SQL proved to be a problem.  The class structure was DEEP.  It took a LOT of SQL code to rebuild the XML, so that the object could be deserialized.  I had to find a better way.

I turned to the ISerializable interface.  By implementing this interface, you can control how your class is serialized.  Cool!  This was the solution to my problem, right?  Wrong!  The ISerializable interface does not work when you use the XMLSerialier.  I wanted XML and the ISerializable interface gave me a binary serialization. 

After thinking a few unmentionable thoughts about the world in general, I finally found a real solution.  There is an undocumented interface called IXmlSerializable.  If you look this up in the .NET help, you will see that they say this is an internal interface and that you should not use it.  However, if you look here, you can see that this interface IS documentated in Longhorn.  Feeling a little better now, I tried it.  It works great.

Serialization Methods:


XmlSchema IXmlSerializable.GetSchema()
{
     return null;
}

void IXmlSerializable.ReadXml(XmlReader Reader)
{
     // code to read in XML document goes here
}

void IXmlSerializable.WriteXml(XmlWriter Writer)
{
     // code to write XML document goes here
}

Now I can have a deep class structure in my code, and serialize this as a very flat XML document.  Then, instructing SQL Server to create this XML document from the database is very simple and easy to maintain.

Comments