I have several elements that have optional child elements and
attributes that are xs:dates.
I have been using System.DateTime and the XmlAttribute/XmlElement
attributes, but these will never work as System.DateTime can never be
null.
So
public class MyClass
{
[XmlAttribute("a")] public string a;
[XmlElement(ElementName="b", DataType="date")] public DateTime b;
}
will return
<MyClass>
<b>0001-01-01</b>
</MyClass>
when I want an empty element.
I have tried my own class (Date) that exposes an XmlText attribute:
public class Date
{
private string dt;
public Date() { }
[XmlText()]
public string Value { get { return dt;} set { dt=value;}}
}
and changed my class to:
public class MyClass
{
[XmlAttribute("a")] public string a;
[XmlElement(ElementName="b")] public Date b;
}
....but the serializer then throws an exception :
"Cannot serialize member 'b'. XmlAttribute/XmlText cannot be used to
encode complex types."
How do I achieve an optional xs:date using XmlSerializer ?