Try this :
[XmlElement(IsNullable = false)]
public Nullable<DateTime> MyDateTime { get; set }
With IsNullable set to false, the property won't be serialized when the value is null
UPDATE : OK, this doesn't work... here's an alternative that should give the desired result :
[XmlIgnore]
public Nullable<DateTime> MyDateTime { get; set }
[XmlElement(ElementName = "MyDateTime", IsNullable = false)]
public string MyDateTimeXml
{
get
{
if (MyDateTime.HasValue)
return XmlConvert.ToString(MyDateTime.Value, XmlDateTimeSerializationMode.Unspecified);
else
return null;
}
set
{
if (value != null)
MyDateTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Unspecified);
else
MyDateTime = null;
}
}
A bit longer, but still easier than implementing IXmlSerializable
;)
UPDATE 2 :
I just stumbled upon this question, where Marc gives an excellent answer. Just add a ShouldSerializeMyDateTime
method to your class :
public bool ShouldSerializeMyDateTime()
{
return MyDateTime.HasValue;
}
Apparently this is an undocumented feature of XML serialization... You can also use a property named MyDateTimeSpecified