简体   繁体   中英

Serialize Complex Type System.Nullable<System.DateTime>

I want to serialize DateTime so that when DateTime is null I dont get the tag itself.

I have also set bool specified for the above but my problem is DateTime being of value type it will never be null hence the bool specified will always be true for it.

I even tried replacing DateTime to System.Nullable but I get Serialization Error when Sending request or receiving response from WebService.

Is there any way out ?

See 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

You will probably need to implement IXmlSerializable and manually serialize your type, you will then be able to use the Nullable<DateTime> . Here's an example:

public class MyData : IXmlSerializable
{
    public Nullable<DateTime> MyDateTime { get; set; }

    public void WriteXml(XmlWriter writer)
    {
        if (this.MyDateTime.HasValue)
        {
            writer.WriteStartElement("MyDateTime");
            writer.WriteValue((DateTime)this.MyDateTime);
            writer.WriteEndElement();
        }
    }

    public void ReadXml(XmlReader reader)
    {
        if (reader.ReadToDescendant("MyDateTime"))
        {
            this.MyDateTime = reader.ReadElementContentAsDateTime();
        }
    }

    public XmlSchema GetSchema()
    {
        return null;
    }
}

Using this:

MyData md = new MyData { MyDateTime = null };
XmlSerializer ser = new XmlSerializer(typeof(MyData));
using (var writer = XmlWriter.Create(@"d:\temp\test.xml"))
{
    ser.Serialize(writer, md);
}

using (var reader = XmlReader.Create(@"d:\temp\test.xml"))
{
    md = (MyData)ser.Deserialize(reader);
    WL(md.MyDateTime.HasValue);
}

Change that first line to MyDateTime = DateTime.Now to see the alternate behaviour. This writes and reads the MyDateTime value depending on whether it's present in the XML:

<?xml version="1.0" encoding="utf-8"?>
<MyData />

<?xml version="1.0" encoding="utf-8"?>
<MyData>
    <MyDateTime>2009-08-06T10:10:14.8311049+01:00</MyDateTime>
</MyData>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM