Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# xml serialization doesn't write null

when I serialize a c# object with a nullable DateTime in it, is there a way to leave the null value out of the xml file instead of having

 <EndDate d2p1:nil="true" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance" />
like image 298
Patrick Avatar asked Oct 03 '11 15:10

Patrick


1 Answers

You can use the Specified extended property to leave out null values (or any other value, for that matter). Basically, create another property with the same name as the serialized property with the word Specified added to the end as a boolean. If the Specified property is true, then the property it is controlling is serialized. Otherwise, if it is false, the other property is left out of the xml file completely:

[XmlElement("EndDate")]
public DateTime? EndDate { get; set; }
[XmlIgnore]
public bool EndDateSpecified { get {
    return (EndDate != null && EndDate.HasValue); } }
like image 185
mellamokb Avatar answered Sep 29 '22 02:09

mellamokb