Reputation: 86085
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
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
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.
Upvotes: 0
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