DataContractSerializerSettings 类示例 [英] DataContractSerializerSettings Class Examples
问题描述
我正在寻找有关如何使用 DataContractSerializerSettings 类的示例.有两个我感兴趣的特定属性
I am looking for example on how to use the DataContractSerializerSettings class. There are two specific properties I am interested in
- 根名称
- 根名称空间.
我可以在我的代码中使用它们来设置输出 xml 中的命名空间吗?
Can I use them in my code to set the namespace in the output xml?
推荐答案
如果您正在创建 DataContractSerializer
,那么可以.您可以创建一个 DataContractSerializerSettings
对象并使用 XmlDictionary
设置 RootName
和/或 RootNamespace
以创建 XmlDictionaryString
s.举个例子:
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);
序列化的 XML 中根元素的名称将为MyRootName",xmlns 属性将为MyNamespace",例如:
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">
请注意,默认命名空间仍将包含在d1p1"别名中,因此我认为无法使用这些设置覆盖该命名空间.最简单的方法是使用 DataContract
属性定义您的类:
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; }
}
这篇关于DataContractSerializerSettings 类示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!