如何忽略序列化可为空的属性,如果它是null或空? [英] How to ignore a nullable property from serialization if it is null or empty?
问题描述
我有用于XML序列化的类。
在里面有我有饰有XmlAttribute可为空属性:
[XmlAttribute(LASTUPDATED)]
公众的DateTime? LASTUPDATED {搞定;组; }
如何忽略序列化的属性,如果它是null或空?
我试过以下,但如果有一个值(始终忽略),它不序列化:
[XmlIgnore]
公众的DateTime? LastUpdatedValue {搞定;组; } [XmlAttribute(LASTUPDATED)]
公众的DateTime LASTUPDATED {搞定;组; } 公共BOOL ShouldSerializeLastUpdated()
{
返回LastUpdatedValue.HasValue;
}
可空不直接XmlSerialization支持。
如果你想使用一个可空属性,你必须使用非可空属性,并使用与后缀属性相同的名字添加一个布尔属性指定,这specifie当属性必须是可序列化。
与你的情况的一个例子:
私人的DateTime? _最近更新时间; [XmlAttribute(LASTUPDATED)]
公众的DateTime LASTUPDATED {
获得{
返回(DATETIME)_LastUpdated;
}
组
{
_LastUpdated =价值;
}
} 公共BOOL LastUpdatedSpecified
{
得到
{
返回_lastUpdated.HasValue;
}
}
I have a class which is used for Xml Serialization.
Inside which I have a nullable property which is decorated with XmlAttribute:
[XmlAttribute("lastUpdated")]
public DateTime? LastUpdated { get; set; }
How to ignore the property from serialization if it is null or empty?
I've tried the below but it doesn't serialize when there is a value (always ignores):
[XmlIgnore]
public DateTime? LastUpdatedValue { get; set; }
[XmlAttribute("lastUpdated")]
public DateTime LastUpdated { get; set; }
public bool ShouldSerializeLastUpdated()
{
return LastUpdatedValue.HasValue;
}
Nullable is not directly supported by XmlSerialization.
If you want use a nullable property you must use a non nullable property and add a boolean property with the same name of property with the suffix "Specified" which specifie when the property must be serializable.
An example with your case :
private DateTime? _lastUpdated;
[XmlAttribute("lastUpdated")]
public DateTime LastUpdated {
get {
return (DateTime)_lastUpdated;
}
set
{
_lastUpdated = value;
}
}
public bool LastUpdatedSpecified
{
get
{
return _lastUpdated.HasValue;
}
}
这篇关于如何忽略序列化可为空的属性,如果它是null或空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!