C# - How to change the default namespace for DataContractSerializer

Why is my object serialized to the XML namespace http://schemas.datacontract.org/2004/07/ ?

E.g.

<?xml version="1.0" encoding="utf-8"?>
<President xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Zuga.net">
    <First>George</First>
    <Last>Washington</Last>
    <Number>1</Number>
    <Year>1789</Year>
</President>

Because this is the default namespace URI prefix for a .NET class using the DataContract attribute.

The MSDN documentation states:
By default, when you apply the DataContractAttribute to a class, it uses the class name as the local name and the class's namespace (prefixed with "http://schemas.datacontract.org/2004/07/") as the namespace URI.
There are 2 ways to change the serialized namespace for a type.
At the Assembly level.
Add the ContractNamespace attribute to the assembly to change the default URI prefix for the entire assembly.
AssemblyInfo.cs
[assembly: ContractNamespace("http://schemas.zuga.net/", ClrNamespace = "Zuga.net")]
At the class level.
Add a Namespace property to the DataContractAttribute on the type to be serialized.
[DataContract(Namespace = "http://schemas.zuga.net/people/")]
public class President
{
    [DataMember] public int Number { get; set; }
    [DataMember] public string First { get; set; }
    [DataMember] public string Last { get; set; }
    [DataMember] public int Year { get; set; }
}

Using method 1, we get:

<?xml version="1.0" encoding="utf-8"?>
<President xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.zuga.net/">
    <First>George</First>
    <Last>Washington</Last>
    <Number>1</Number>
    <Year>1789</Year>
</President>

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath