DataContractSerializerSettings Class Examples

痴心易碎 提交于 2021-01-28 05:30:27

问题


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?


回答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 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; }
}


来源:https://stackoverflow.com/questions/18969845/datacontractserializersettings-class-examples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!