Andy @ Work

Tuesday, November 29, 2005

Traps to look out for when implementing IXmlSerializable for a Web Service

I’ve been working on this new project in .Net 2.0, and am loving the flexibility that the IXmlSerializable interface gives me. Before this interface, I either had to let the XmlSerializer dictate the design of some of my business layer classes, or create very a series of Data Transfer Objects (DTO’s). Most of the time I've gone down the DTO path so that other users of my business layers didn’t accidentally start using methods that were not designed for them to use.

Anyway. After implementing a couple IXmlSerializable interfaces on what I would consider complex types (not very complex ~ just not simple) I have come across the following traps/tricks.

  • WriteXml When you implement this method, make sure you include the default namespace in your Write... methods. This has caused me so many hassels in the past. Its easy to forget, but if you don't do it you won't be able to send serialized types to your consumers.

  • DateTimesWhen serializing and deserializing DateTime’s you normally use the XmlConvert class. Make sure you use the ToDateTime method that will take a XmlDateTimeSerializationMode enum as a parameter, and set that enum to RoundtripKind. Otherwise you will get a lot of FormatExceptions when deserializing a Datetime on your side of the webservice.

  • Try to avoid using attributes in your schema over elements. Personally I think that attributes look neater than a whole string of xml elements, but its easier to read elements using the XmlReader than it is to using Attributes.

If I have time I would like to investigate that third point a little more to confirm that there is problem with the order in which enum elements in the schema are defined.


Post a Comment

<< Home