user2953119
user2953119

Reputation:

How to hide a property into a base class for XML serialization

Let I've a base class

public class MyClass
{
    private bool _success;
    public bool Success
    {
        get { return _success; }
        set { _success = value; }
    }
}

and a derived class

public class MySubClass : MyClass
{
    public string str { get; set; }
}

Question: How can I to serialize MySubClass to XML such that there is no <Success> tag in the serialization result?

Upvotes: 4

Views: 4287

Answers (2)

middelpat
middelpat

Reputation: 2585

[XmlIgnore]
public bool Success
{
    get { return _success; }
    set { _success = value; }
}

The [XmlIgnore] attribute tells the serialization process to ignore this attribute. It will never be serialized so there won't be a node in your serialized XML

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx

To ignore the field only in your subclass, you can override the property from the baseclass.

In your base class (note the virtual keyword):

public virtual bool Success {get;set;}

In you subclass

[XmlIgnore]
public override bool Success {get;set;}

Upvotes: 9

J&#252;rgen Steinblock
J&#252;rgen Steinblock

Reputation: 31723

If you don't have access to your base class, you can add a ShouldSerializePropertyName method to your class.

public bool ShouldSerializeSuccess()
{
    return false;
}

By convention XmlSerializer will execute any ShouldSerialize... method to determine if the property should be serialized. You can even do something conditionally:

// this will serialize sucess only if it is true.
public bool ShouldSerializeSuccess()
{
    return Sucess;
}
public bool ShouldSerializeName()
{
    return !String.IsNullOrWhiteSpace(Name) && !Name.Equals("Default");
}

Upvotes: 2

Related Questions