Previous month:
May 2006
Next month:
July 2006

June 2006

Shaping data for the DataContractSerializer (and thus WCF)

The other day we came across this small thing while writing some sample code for our docs.

We can control the way our CLR arrays are serialized in a well-known way by using XmlSerializer and the XmlArrayAttribute and XmlArrayItemAttribute attributes.
For example having a type like this...

public class Family
  [XmlArray(ElementName = "Members")]
  [XmlArrayItem(ElementName = "Name")]
public string[] Members;

...could produce XML as follows by leveraging XmlSerializer.

<Family xmlns:xsi="" xmlns:xsd="">

Now, if we define a bare WCF data contract to represent the same family it would look like this:

class Family
  public string[] Members;

The DataContractSerializer (DCS) produces the following XML for an instance of the Family class:

<Family xmlns:i="" xmlns="">
  <Members xmlns:d2p1="">

But if we want to make it look equivalent to the XML generated for the XmlSerializer-based Family document instance, how could we do that?

There is a solution. Looking at the following screenshot from Lutz's fantastic Reflector we can see there are some attributes we can use to massage the XML spit out by DCS.

WCF's DataContractSerializer attributes

So, instead of using an array, you need to use a collection type marked with the CollectionDataContractAttribute (you can derive a type from an existing collection type and add the attribute). The attribute has properties that can be used to customize array item names, etc.


class Family
  public MemberList Members;

class MemberList : List<string> { }

Feel free to download a small demo solution for WinFX Beta 2.