2

I'm doing the following to ignore a couple of elements on serialization only:

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

The class properties do not have the XmlElement attribute. The property name also matches the string passed to overrides.Add.

However, the above is not ignoring the property and it's still serialized.

What am I missing?

dbc
  • 104,963
  • 20
  • 228
  • 340
Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263

1 Answers1

3

The type to pass in to XmlAttributeOverrides.Add(Type type, string member, XmlAttributes attributes) is not the type that the member returns. It's the type in which the member is declared. Thus to ignore MyProperty in both Parent and Child you must do:

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

Note that, if you construct an XmlSerializer with overrides, you must cache it statically to avoid a severe memory leak. See Memory Leak using StreamReader and XmlSerializer for details.

Sample fiddle.

Community
  • 1
  • 1
dbc
  • 104,963
  • 20
  • 228
  • 340
  • After many days of fighting the serializer, I found out there was a bug that did the same thing with derived classes. If a property is inherited, it is not enough to override the attribute of the property in the class being serialized. You must override the property in its _base_ class to make the serializer recognize the new attribute, mangling the normal advantages of subclassing. – Suncat2000 Mar 05 '20 at 16:01