Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XmlIgnoreAttribute to Ignore Base Class Property

I have an abstract base class to which I have added some virtual properties. What I would like is to, in my derived class, specify that a particular base class property be ignored during the serialization(and deserialization process). As you see below, the Value-property in BaseClass-class is declared a virtual property, and in the DerivedClass-class, using the overrides-keyword, I have chosen to override the base class's ppty and then put the XmlIgnoreAttribute-Attribute over it. However, when I test the code, I still find the Value ppty included in the generated XML for my derived class instance. Same thing happens with the Definition ppty, it is rendered even though I hide it in the Derived class using the new keyword, and then apply the XMLIgnoreAttribute to it as well. What is wrong with the code below please?

public abstract class BaseClass
{
    public virtual String Value { get; set; }

     public String Definition { get; set; }

    [XmlAttribute("SeparatorCharacter")]
    public virtual String SeparatorCharacter { get; set; }
}


public class DerivedClass:BaseClass
{
    [XmlIgnore()]
    public overrides String Value { get; set; }

    [XmlAttribute("FillerCharacter")]
    public String FillValue { get; set; }

     [XmlIgnore()]
    public new String Definition { get; set; }
}
like image 334
Kobojunkie Avatar asked Nov 01 '25 04:11

Kobojunkie


1 Answers

The serializer will not consider the attribute on the override property, whether you supply it with an attribute or through XmlAttributeOverrides. The only partial workaround to obtain the behavior you want is to add a virtual ShouldSerializeValue method to the base class and override it in the derived class to suppress the serialization of Value. This won't prevent deserialization of Value, but you can make the override setter empty.

public abstract class BaseClass
{
    public virtual String Foo { get; set; }
    public virtual bool ShouldSerializeFoo () { return true ; }
}

public class DerivedClass:BaseClass
{
    public override String Foo { get; set; }
    public override bool ShouldSerializeFoo () { return false ; }
}
like image 194
Anton Tykhyy Avatar answered Nov 03 '25 18:11

Anton Tykhyy