Jakew
Consulting, hacking, and motorcycles

Friggin XmlSerializer & XSDs

Sunday, 9 September 2007 12:12 by jakew

Sense I work with BizTalk most of the time I have to work with real XSDs that have actual namespaces. Which actually rocks because I don’t have to worry about name collisions too much. The down side though is when you need to serialize and deserialize an XML file that happens to contain one of your messages.

Typically I just write something like:

XmlSerializer serializer = new XmlSerializer(typeof(SnotRocket));

SnotRocket sr = (SnotRocket) serializer.Deserialize(reader);

For normal hand written XML this is fine, but if the message is following a real XSD it has a namespace and the serializer won’t be able to read it. The solution is to fix up the constructor:

XmlSerializer serializer = new XmlSerializer(typeof(SnotRocket), “http://Rhinoplasty”);

SnotRocket sr = (SnotRocket) serializer.Deserialize(reader);

And things get back to rockin. Why is this worth mentioning? Well, in order to do this you have to run the XSD through the XSD tool which generates the classes and stuff for you which tell XmlSerializer what to do. Why can’t XmlSerializer look at the attributes attached to the root object to get the root namespace? Oh, well.

Minor stuff, but to help me remember this little tid bit (I've hit my head on this often enough) I wrote this to share and help me remember for next time.

Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed