我想用XmlSerializer的创造排除属性,如果他们有一个默认值的XML。这可能与XmlSerializer的还是我将不得不考虑的IXmlSerializable?
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;}
}
我想告诉XmlSerializer的,当它系列化PositionedObject的实例,不包括X如果该值为0(与同为Y,如果是0)。
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).
只是声明 ShouldSerializeX
返回true命名的方法,当值不为0:
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.