How can I ignore properties according to their value with XmlSerializer

家住魔仙堡 提交于 2020-01-22 18:50:27

问题


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


回答1:


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.




回答2:


One other supported XmlSerializer pattern;

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

Note however that your parameterless constructor must assign this value, or unpredictable results will occur.




回答3:


Your class can implement IXmlSerializable and in WriteXml method choose not to serialize out attributes that have whatever you consider as default.

public class PositionedObject : IXmlSerializable
{

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

In your position is a float pair and you might have to use some tolerance




回答4:


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.



来源:https://stackoverflow.com/questions/8553828/how-can-i-ignore-properties-according-to-their-value-with-xmlserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!