问题
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