In light of
this discussion on serialization and element order, I thought it might be interesting to point out how DataContractSerializer (DCS), previously known as XmlFormatter, works in WCF.
First, XmlSerializer (from .NET 1.1 and 2.0) serializes data members based on the reflection process, which is basically fields grouped first followed by properties where each group is in the same order as the original class definition. .NET 2.0 introduced the Order property for overriding this default order.
DCS, on the other hand, serializes data members in alphabetical order regardless of how they show up in the source file. The fact that they've defined a canonical element order for a serializable type should alleviate most of
Craig's concerns. For example, consider the following class:
[DataContract]
public class Person
{
[DataMember]
public string Name;
[DataMember]
public double Age;
}
In this case, the order the <Person> child elements will be <Age> followed by <Name>.
With DCS, you can also use the Order attribute to override the default ordering but it works a bit differently. All data members marked with the same Order value will be ordered as a group alphabetically.
[DataContract]
public class Person
{
[DataMember(Order=1)]
public string Name;
[DataMember(Order = 1)]
public double Age;
[DataMember(Order = 2)]
public double Weight;
[DataMember(Order = 2)]
public string HairColor;
}
In this case, the order of the <Person> child elements will be <Age>, <Name>, <HairColor>, then <Weight>. This was designed to provide versioning flexibility when adding new elements to a schema type -- the Order value essentially represents the version. Using this technique, elements added in a future version will always appear at the end of the schema type.
Posted
Apr 18 2006, 03:10 PM
by
Aaron Skonnard