Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ignore properties according to their value with XmlSerializer

I'd like the XML created by XmlSerializer to exclude properties if they have a default value. Is this possible with XmlSerializer or am I going to have to look into IXmlSerializable?

For example, I may have the following class:

public class PositionedObject
{
   public float X
   { get; set; }

   public float Y
   { get; set;}
}

I'd like to tell the XmlSerializer that when it serializes an instance of PositionedObject, to not include X if the value is 0 (and same with Y if it is 0).

like image 341
Victor Chelaru Avatar asked Dec 18 '11 18:12

Victor Chelaru


People also ask

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization. Note this is the kind of thing I meant. You are not telling the XmlSerializer to ignore namespaces - you are giving it XML that has no namespaces.

How to ignore property in XML serialization c#?

To override the default serialization of a field or property, create an XmlAttributes object, and set its XmlIgnore property to true . Add the object to an XmlAttributeOverrides object and specify the type of the object that contains the field or property to ignore, and the name of the field or property to ignore.

What is the use of XmlIgnore?

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.

Is XmlSerializer thread safe?

Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application.


2 Answers

Thomas' way is probably simplest way to what you want. However you may want to consider that technically value types always have a value, and you probably should serialize it. Note that XmlSerializer will skip adding X element if you were to declare it as string or other reference type.
Of course declaring X coordinate as string would be silly, but you can declare it as nullable float?, which will serialize as <X xsi:nil="true" />, which may be closer to what you actually want... unless you just want to make your XML pretty looking, then got with Thomas' suggestion.

like image 146
Ilia G Avatar answered Nov 01 '22 10:11

Ilia G


Just declare a method named ShouldSerializeX that returns true when the value is not 0:

public bool ShouldSerializeX()
{
    return X != 0;
}

The serializer will call this method to decide whether the property should be serialized or not.

like image 31
Thomas Levesque Avatar answered Nov 01 '22 10:11

Thomas Levesque