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).
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.
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.
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.
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.
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.
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.
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