Serializing Collections: Customizing Serialization of Collection Types

Description Article
Table of Contents
Summary

A collection type can be customized using the CollectionDataContract attribute instead of the DataContrac attribute.

The CollectionDataContract attribute has Name and Namespace properties.

Operations
Collection Data Contract Naming: Default naming of collections during serialization

When the attribute is not applied, the default name and namespace for collection types depend on the names and namespaces of types contained within the collection. They are not affected by the name and namespace of the collection type.

How to do it
public CustomerList1 : Collection<string> {}

public StringList1 : Collection<string> {}
<ArrayOfstring>
    <string>...</string>
    <string>...</string>
    <string>...</string>
    ...
</ArrayOfstring>
Collection Data Contract Naming: Customizing naming of collections during serialization

When the CollectionDataContract attribute is applied, the collection becomes a customized collection data contract, even if no properties are set on the attribute:

The name and namespace of the collection data contract then depend on the collection type itself.

How to do it
[CollectionDataContract]
public class CustomerList2 : Collection<string> {}
<CustomerList2>
    <string>...</string>
    <string>...</string>
    <string>...</string>
    ...
</CustomerList2>
Collection Data Contract Naming: Customizing naming of collections during serialization (specific root name)
How to do it
[CollectionDataContract(Name="cust_list")]
public class CustomerList3 : Collection<string> {}
<cust_list>
    <string>...</string>
    <string>...</string>
    <string>...</string>
    ...
</cust_list>
Customizing the Repeating Element Name in List Collections

List collections contain repeating entries and each repeating entry is by default represented as an element named according to the data contract name of the type contained in the collection.

How to do it
[CollectionDataContract(ItemName="customer")]
public class CustomerList4 : Collection<string>  {}
<CustomerList4>
    <customer>...</ customer>
    <customer>...</customer>
    <customer>...</customer>
    ...
</CustomerList4>
Customizing Dictionary Collections

Dictionary collections are lists of entries, where each entry has a key followed by a value.

The element name as well as the key and value names can be changed.

How to do it
[CollectionDataContract
    (Name = "CountriesOrRegionsWithCapitals",
    ItemName = "entry",
    KeyName = "countryorregion",
    ValueName = "capital")]
public class CountriesOrRegionsWithCapitals2 : Dictionary<string, string> { }

 

<CountriesOrRegionsWithCapitals>
    <entry>
        <countryorregion>USA</countryorregion>
        <capital>Washington</capital>
    </entry>
    <entry>
        <countryorregion>France</countryorregion>
        <capital>Paris</capital>
    </entry>
    ...
</CountriesOrRegionsWithCapitals>