以编程方式在c#中添加[XmlIgnore]属性以进行序列化

时间:2014-01-28 13:37:33

标签: c# xml xml-serialization

有谁知道如何以编程方式将[XmlIgnore]属性添加到c#中的类属性中?

我想这样做只有一个有一个或两个字段的类可以在运行时进行序列化。

非常感谢提前。

1 个答案:

答案 0 :(得分:7)

可以通过将XmlAttributeOverrides对象传递给XmlSerializer构造函数来动态覆盖XML序列化属性。

XmlAttributes samplePropertyAttributes = new XmlAttributes();
samplePropertyAttributes.XmlIgnore = true;

XmlAttributeOverrides sampleClassAttributes = new XmlAttributeOverrides();
sampleClassAttributes.Add(typeof(SampleClass), "SampleProperty", samplePropertyAttributes);

var serializer = new XmlSerialized(typeof(SampleClass), sampleClassAttributes);

有关详细信息,请参阅XmlAttributeOverrides Class in MSDN

相关问题