how to serialize some attribute in some condition
When usin开发者_如何转开发g 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.
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"; }
}
}
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.
You can use OnSerializingAttribute while serializing which allows us to invoke method before serialization. You can get more information about it here
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
精彩评论