I have a rather large class to serialize as Xml, and in order to reduce the wasted space would like to selectively XmlIgnore some of the class properties. For example, one property in the class is assigned a value only one out of ten times or so, and if I code the serialization attribute as follows
[XmlAttribute]
public String WorkClass
{
get { return _workClass; }
set { _workClass = value; }
}
If there is no value (most of the time) this is serialized over and over again as
WorkClass=""
Is there an option or attribute that would ignore the property for serialization if its value is empty, but not ignore it if it is not empty?
Allows the XmlSerializer to recognize a type when it serializes or deserializes an object.
The XmlIgnoreAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. If you apply the XmlIgnoreAttribute to any member of a class, the XmlSerializer ignores the member when serializing or deserializing an instance of the class.
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.
You can create methods for each of the values you wish to not have serialized
The following method will return true
when WorkClass
contains something other than an empty string, if you're using .NET Framework 4, you could elect to use string.IsNullOrWhitespace()
which would also check for blank spaces ' '
.
public bool ShouldSerializeWorkClass() {
return !string.IsNullOrEmtpy(WorkClass);
}
When the Xml Serializer runs, it will look for this method, based on the naming convention and then choose whether to serialize that property or not.
The name of the method should always begin with ShouldSerialize
and then end with the property name. Then you simply need to return a boolean based on whatever conditional you want, as to whether to serialize the value or not.
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