How can I ignore properties according to their value using XmlSerializer

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

+5
source share
4 answers

Just declare a method with a name ShouldSerializeXthat returns true when the value is not 0:

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

, , .

+9

XmlSerializer;

[DefaultValue({whatever})]
public SomeType SomeProperty {get;set;}

, , .

+7

IXmlSerializable WriteXml , , .

public class PositionedObject : IXmlSerializable
{

  public void WriteXml(System.Xml.XmlWriter writer)
  {
        if (  Position != DefaultPosition )
          writer.WriteAttributeString("Position", Position);
  }
}

,

+1

- , , , . , , , , . , XmlSerializer X, string .
, X- , nullable float?, <X xsi:nil="true" />, , ... XML , .

0

All Articles