【问题标题】:Using XmlAttributeOverrides to ignore elements not working使用 XmlAttributeOverrides 忽略不起作用的元素
【发布时间】:2017-02-04 12:11:49
【问题描述】:

我正在执行以下操作以仅忽略序列化中的几个元素:

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);

类属性没有XmlElement 属性。属性名称也与传递给 overrides.Add 的字符串匹配。

但是,上面没有忽略该属性,它仍然是序列化的。

我错过了什么?

【问题讨论】:

  • 在代码示例中 MyParent 应该是 Parent?

标签: c# xml xmlserializer


【解决方案1】:

传递给XmlAttributeOverrides.Add(Type type, string member, XmlAttributes attributes) 的类型不是成员返回的类型。它是成员声明的类型。因此,要在 ParentChild 中忽略 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

【讨论】:

  • 在与序列化程序斗争了很多天之后,我发现有一个错误与派生类做同样的事情。如果一个属性被继承,仅仅覆盖被序列化的类中该属性的属性是不够的。您必须覆盖其 base 类中的属性,以使序列化程序识别新属性,从而破坏子类化的正常优势。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 2013-05-16
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
相关资源
最近更新 更多