Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one use XmlAttributes to selectively XmlIgnore?

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?

like image 451
Cyberherbalist Avatar asked Mar 12 '12 17:03

Cyberherbalist


People also ask

What is the use of XmlIgnore?

Allows the XmlSerializer to recognize a type when it serializes or deserializes an object.

What is XmlIgnore attribute?

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.

What is XML write a brief note on XML serialization?

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.

What is XML serialization in c#?

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.


1 Answers

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.

like image 89
Anthony Shaw Avatar answered Sep 28 '22 06:09

Anthony Shaw