Now, in .net 2.0, we have the option to fully implement
IXmlSerializable on our custom types! This is great for controlling the exact values you want serialized, and for when the default serializer just wont cut it. In most cases, using the Xml Attributes to customize serialization work just fine, but I had a scenario where I needed to serialize data on my type that could not be serialized by default...so, I turned to
IXmlSerializable, and my adventure began.
The Interface itself, requires that you implement 3 methods: GetSchema (backwards compatibility only), ReadXml, WriteXml, and that you apply the
XmlSchemaProvider attribute to the class declaration. The Read/Write Xml methods are simple enough to implement and just as you would expect, you are handed an XmlReader to parse or an XmlWriter to create an xml document based on your type. The sneaky bastich part of it all is the implementation of the schema provider method defined the XmlSchemaProvider attribute. Now, I don't know if you've ever build a schema programatically before, but if you haven't, I will give you this warning...THERE's A *** CLOUD COMING!...RUN FOR YOUR LIVES!...Building this schema just right, which is extremely non-intuitive btw, and configuring the Read/Write methods to match the definition was as close to Hell as I care to get. I did eventually figure it out, and for the most part the problems were just minor quirks that I was not aware of (once I figured how to code the schema properly that is); for example, whatever you do, do not close the writer at the end of the WriteXml method! You will get a runtime error that makes very little sense and contemplate computer homicide soon after the 30th error box pops in your face. And I would definitely recommend writing the schema xml style first, before attempting to write it via code.
Anyway, the whole thing was definitely a learning experience and, as it turns out, I didn't even need custom serialization once I shifted the design of my app. Stupid .net. ;)