user496949
user496949

Reputation: 86085

how to serialize some attribute in some condition

When using XML serialization to serialize a class, how to make some attribute be outputted conditionally. i.e. In some case, it output this attribute, in other cases, it does not.

Upvotes: 7

Views: 4691

Answers (4)

Tamás Szelei
Tamás Szelei

Reputation: 23941

While works and is a rather short solution, the propertyNameSpecified pattern has some drawbacks in my opinion (pollutes the interface of your class; relies on property names; introduces implicit behavior).

If you only need to implement a simple condition (e.g. don't serialize a default value), then the DefaultValue attribute is a better choice.

For example:

public class PurchaseOrder
{
    [DefaultValue("2002")]
    public string Year;
}

If Year has the value "2002", it will be omitted from the XML output.

Upvotes: 4

Anton
Anton

Reputation: 5623

Imho you would need to implement IXmlSerializable on the class and implement the WriteXml and ReadXml methods in such a way that they only write the attribute based upon the conditions you specify and can handle reading with or without that particular attribute present upon deserialization.

IXmlSerializable at Msdn

Upvotes: 0

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

You can create an additional property which is called MyPropertySpecified, which returns a boolean.
When this property returns true, the MyProperty property will be serialized. When it returns false, it will not be serialized.

Also, you'd want to decorate that property with the XmlIgnoreAttribute, so that this specific property is not serialized.

Example:

public class Person
{
    public string Name
    {
        get;
        set;
    }

    [XmlIgnore]
    public bool NameSpecified
    {
        get  { return Name != "secret"; }
    }
}

Upvotes: 13

Shekhar
Shekhar

Reputation: 11788

You can use OnSerializingAttribute while serializing which allows us to invoke method before serialization. You can get more information about it here

Upvotes: 0

Related Questions