Frage

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?

War es hilfreich?

Lösung

[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;}

Andere Tipps

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");
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top