Reputation: 12309
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?
Upvotes: 8
Views: 2660
Reputation: 8166
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.
Upvotes: 11