I want the XML created by XmlSerializer to exclude properties if they have a default value. Is this possible with XmlSerializer or will I have to search in IXmlSerializable?
For example, I might have the following class:
public class PositionedObject { public float X { get; set; } public float Y { get; set;} }
I would like to tell XmlSerializer that when it serializes an instance of PositionedObject, do not include X if the value is 0 (and the same with Y if it is 0).
Just declare a method with a name ShouldSerializeXthat returns true when the value is not 0:
ShouldSerializeX
public bool ShouldSerializeX() { return X != 0; }
, , .
XmlSerializer;
[DefaultValue({whatever})] public SomeType SomeProperty {get;set;}
IXmlSerializable WriteXml , , .
IXmlSerializable
WriteXml
public class PositionedObject : IXmlSerializable { public void WriteXml(System.Xml.XmlWriter writer) { if ( Position != DefaultPosition ) writer.WriteAttributeString("Position", Position); } }
,
- , , , . , , , , . , XmlSerializer X, string ., X- , nullable float?, <X xsi:nil="true" />, , ... XML , .
XmlSerializer
X
string
float?
<X xsi:nil="true" />