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.
You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.
Ignore individual properties You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored. If no Condition is specified, this option is assumed.
You can serialize a populated DataSet object to an XML file by executing the DataSet object's WriteXml method. You can serialize a populated DataSet object to an XML file by executing the DataSet object's WriteXml method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With