I am doing some custom serialization with the DataContractSerializer
through use of the IXmlSerializable
interface.
For example:
public class CustomPartOfAContract : IXmlSerializable
{
public void WriteXml( XmlWriter writer )
{
//...
}
public void ReadXml( XmlReader reader )
{
//...
}
}
[DataContract(Namespace="http://mynamespace.com")]
public class MyDataContract
{
[DataMember(IsRequired=true)]
public ICollection<CustomPartOfAContract> CustomParts { get; set; }
}
Now, in the WriteXml
method I can tell the XmlWriter
what namespace to use for each element I write. However I can't figure out how to specify the namespace for CustomPartOfAContract
.
Outputting the XML to file, the namespace for the CustomParts
property in MyDataContract
is being generated from the source code namespace.
Anyone any idea how I can specify the namespace to use when serializing this?
Ok, I solved this by adding a custom collection class which inherits from Collection
and applying the [CollectionDataContract]
attribute with the correct namespace:
[CollectionDataContract( Namespace="http://mynamespace.com" )]
public class MyCustomPartsCollection : Collection<CustomPartOfAContract>
{
public MyCustomPartsCollection()
{
// We need a default constructor or the serializer complains.
}
}
And then using that in my data contract:
[DataContract(Namespace="http://mynamespace.com")]
public class MyDataContract
{
[DataMember(IsRequired=true)]
public MyCustomPartsCollection CustomParts { get; set; }
}
This seems to apply the correct namespace to the collection class rather than taking the namespace from the source code.