Tuesday, February 09, 2010

XSD, WCF, and The XSD Tool

I'll make this short. If you are creating serialized data (XML) using DataContracts there are five things you need to be aware of upfront if creating XSD files using the XSD tool against the CLR DLL:

  • If your properties names are different than the DataMember names, the XSD will use the DataMember name while the XML will be using the property name. Solution: Keep the DataMember names the same as the property names.
  • Also for DataMembers, use the Order attribute AT ALL TIMES. This gives you the flexibility of populating and ordering property logic as you wish but ensures that the output is always in the same order - which is critical since MS XSD validation does not support the xs:all attribute allowing any ordering of elements.
  • If you are using private properties in the CLR class (I frequently use Count in my CollectionDataContracts for internal use) be aware that the XSD tool will think they will be serialized and dutifully put them into the XSD as expected elements.
  • If you are serializing from an inherited class the XSD types must list all base class elements first and then all derived class elements. I got burned trying to be cute by mix-and-matching properties from both in a mixed order.
  • Stay away from properties that are List(Of) base types, for example List(Of String). There appears to be no way to model this in an XSD. Create a class to store the string and convert the property to List(Of class).

If you haven't worked with XSD files this list will make little sense but read these tips right before going that route and it'll make a helluva lot of sense.