使用 XmlAttributeOverrides 忽略不起作用的元素
Using XmlAttributeOverrides to ignore elements not working
我正在执行以下操作以仅忽略序列化中的几个元素:
public class Parent
{
public SomeClass MyProperty {get;set;}
public List<Child> Children {get;set;}
}
public class Child
{
public SomeClass MyProperty {get;set;}
}
public class SomeClass
{
public string Name {get;set;}
}
XmlAttributes ignore = new XmlAttributes()
{
XmlIgnore = true
};
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(SomeClass), "MyProperty", ignore);
var xs = new XmlSerializer(typeof(MyParent), overrides);
class 属性没有 XmlElement
属性。 属性 名称也匹配传递给 overrides.Add
.
的字符串
但是,上面没有忽略属性,它仍然是序列化的。
我错过了什么?
传递给 XmlAttributeOverrides.Add(Type type, string member, XmlAttributes attributes)
的类型不是成员 returns 的类型。它是 声明 成员的类型。因此,要忽略 Parent
和 Child
中的 MyProperty
,您必须执行以下操作:
XmlAttributes ignore = new XmlAttributes()
{
XmlIgnore = true
};
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
//overrides.Add(typeof(SomeClass), "MyProperty", ignore); // Does not work. MyProperty is not a member of SomeClass
overrides.Add(typeof(Parent), "MyProperty", ignore);
overrides.Add(typeof(Child), "MyProperty", ignore);
xs = new XmlSerializer(typeof(Parent), overrides);
请注意,如果您构造一个带有覆盖的 XmlSerializer
,您必须静态缓存它以避免严重的内存泄漏。有关详细信息,请参阅 Memory Leak using StreamReader and XmlSerializer。
示例 fiddle.
我正在执行以下操作以仅忽略序列化中的几个元素:
public class Parent
{
public SomeClass MyProperty {get;set;}
public List<Child> Children {get;set;}
}
public class Child
{
public SomeClass MyProperty {get;set;}
}
public class SomeClass
{
public string Name {get;set;}
}
XmlAttributes ignore = new XmlAttributes()
{
XmlIgnore = true
};
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(SomeClass), "MyProperty", ignore);
var xs = new XmlSerializer(typeof(MyParent), overrides);
class 属性没有 XmlElement
属性。 属性 名称也匹配传递给 overrides.Add
.
但是,上面没有忽略属性,它仍然是序列化的。
我错过了什么?
传递给 XmlAttributeOverrides.Add(Type type, string member, XmlAttributes attributes)
的类型不是成员 returns 的类型。它是 声明 成员的类型。因此,要忽略 Parent
和 Child
中的 MyProperty
,您必须执行以下操作:
XmlAttributes ignore = new XmlAttributes()
{
XmlIgnore = true
};
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
//overrides.Add(typeof(SomeClass), "MyProperty", ignore); // Does not work. MyProperty is not a member of SomeClass
overrides.Add(typeof(Parent), "MyProperty", ignore);
overrides.Add(typeof(Child), "MyProperty", ignore);
xs = new XmlSerializer(typeof(Parent), overrides);
请注意,如果您构造一个带有覆盖的 XmlSerializer
,您必须静态缓存它以避免严重的内存泄漏。有关详细信息,请参阅 Memory Leak using StreamReader and XmlSerializer。
示例 fiddle.