问题
I am looking for example on how to use the DataContractSerializerSettings class. There are two specific properties I am interested in
- RootName
- RootNameSpace.
Can I use them in my code to set the namespace in the output xml?
回答1:
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 XmlDictionaryString
s. 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; }
}
来源:https://stackoverflow.com/questions/18969845/datacontractserializersettings-class-examples