C# 使用XmlAttributeOverrides忽略不起作用的元素
我正在执行以下操作,以仅忽略序列化中的几个元素:C# 使用XmlAttributeOverrides忽略不起作用的元素,c#,xml,xmlserializer,C#,Xml,Xmlserializer,我正在执行以下操作,以仅忽略序列化中的几个元素: 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 stri
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);
公共类父类
{
公共SomeClass MyProperty{get;set;}
公共列表子项{get;set;}
}
公营儿童
{
公共SomeClass MyProperty{get;set;}
}
公共类
{
公共字符串名称{get;set;}
}
XmlAttributes ignore=新的XmlAttributes()
{
XmlIgnore=true
};
XmlAttributeOverrides overrides=新的XmlAttributeOverrides();
Add(typeof(SomeClass),“MyProperty”,ignore);
var xs=新的XmlSerializer(typeof(MyParent),重写);
类属性没有xmlement
属性。属性名称还与传递给覆盖的字符串相匹配。添加
但是,上面的代码并没有忽略该属性,它仍然是序列化的
我缺少什么?要传入的类型不是成员返回的类型。它是声明成员的类型。因此,要在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
,则必须静态缓存它以避免严重的内存泄漏。有关详细信息,请参阅
示例。代码示例中的MyParent
应该是Parent
?在与序列化程序斗争了很多天之后,我发现有一个bug对派生类做了同样的事情。如果继承了某个属性,则仅重写正在序列化的类中该属性的属性是不够的。您必须重写其基类中的属性,以使序列化程序识别新属性,从而破坏子类化的正常优势。