Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


Ignore inherited property with XmlSerializer
Given class BaseClass with property 'Property1', and a child class MyClass : BaseClass (inherits from BaseClass), when you run the .NET XmlSerializer on MyClass, it will include Property1 in the xml output.
What if you do NOT want Property1 in the output? Overridding the property in MyClass and setting XmlIgnore does not work. Nor does adding the Available/Specified functions to MyClass.
When you create the XmlSerializer, you will have to tell it to explicitly ignore the field on the base class. It will ignore it for any object it finds of that type:

XmlAttributes attrs = new XmlAttributes();
attrs.XmlIgnore = true; // you can add any attributes you want here; allowing you to 'customize' the BaseClass element
XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(BaseClass), "Property1", attrs);
XmlSerializer xSerializer = new XmlSerializer(typeof(Patient), attrOverrides);

... and now xSerializer will exclude property1 when it serializes any class inheriting from BaseClass (or BaseClass itself).

Created By: amos 3/2/2010 5:05:07 PM
Updated: 3/2/2010 5:05:45 PM