Yonatan Shorani
Yonatan Shorani

Reputation: 67

.net XmlSerialize, ignore class properties

Assuming we have two classes Apple, Pineapple

public class Apple:Fruit{}
public class Pineapple:Fruit{}

And we have an abstract class named Fruit

[XmlInclude(typeof(Apple))]
[XmlInclude(typeof(Pineapple))]
public abstract class Fruit{}

And we have a class named Menu

public class Menu 
{
    [XmlElement("apple",typeof(Apple))]
    [XmlElement("",typeof(Pineapple))]
    public Fruit fruit {get;set;}
}

I'd like to ignore the fruit property when the type is Pineapple.

Upvotes: 1

Views: 75

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292385

Not sure why you would want to do that, but you can use the ShouldSerialize<PropertyName> pattern to achieve it:

public class Menu 
{
    [XmlElement("apple",typeof(Apple))]
    public Fruit fruit {get;set;}

    public bool ShouldSerializefruit()
    {
        return !(fruit is Pineapple);
    }

}

Upvotes: 1

Related Questions