abhi
abhi

Reputation: 3136

DataContractSerializerSettings Class Examples

I am looking for example on how to use the DataContractSerializerSettings class. There are two specific properties I am interested in

  1. RootName
  2. RootNameSpace.

Can I use them in my code to set the namespace in the output xml?

Upvotes: 1

Views: 2581

Answers (1)

DigitalDan
DigitalDan

Reputation: 2647

If you're creating the DataContractSerializer, then yes. You can create a DataContractSerializerSettings object and set the RootName and/or RootNamespace using an XmlDictionary to create the XmlDictionaryStrings. Here's an example:

var settings = new DataContractSerializerSettings();
var xmlDictionary = new XmlDictionary();
settings.RootName = xmlDictionary.Add("MyRootName");
settings.RootNamespace = xmlDictionary.Add("MyNamespace");
var serializer = new DataContractSerializer(typeof(MyClass), settings);

The name of the root element in the serialized XML will be "MyRootName" and the xmlns attribute will be "MyNamespace", for example:

<MyRootName xmlns:d1p1="MyDefaultNamespace" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="MyNamespace">

Note that the default namespace will still be included with the "d1p1" alias, so I don't think it's possible to override that namespace using these settings. The easiest place to do that is wherever your class is defined using the DataContract attribute:

[DataContract(Namespace = "MyDefaultNamespace")]
public class MyClass
{
    public string MyProperty { get; set; }
}

Upvotes: 2

Related Questions