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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With