Darren Young
Darren Young

Reputation: 11090

C# XML De-serializing SQL Date field into C# Datetime

I have an SQL view with a field as such:

To_char(date, 'MM-DD-YYYY')

I have a C# object with a DateTime property. The objects are created based on data retrieved from the database being serialized and then being de-serialized into the object. All works well apart from the DateTime field. Depending on the format of the date returned from the DB, I either get an invalid XML error, or the date is set as 01-01-0001

Edit: Additional code as a response to comment.

De-serialize method:

public static object DeSerialize<T>(string data)
    {

       StringReader rdr = new StringReader(data);
       XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
       var result = (T)xmlSerializer.Deserialize(rdr);
       return result;



    }

Class to be de-serialized:

public class VolumeData
{
    public string name { get; set; }
    public string study { get; set; }
    public string group { get; set; }
    public double volume { get; set; }
    public DateTime date { get; set; }
}

Used as such:

List<VolumeData> volumeDataCollection = (List<VolumeData>)Serializer.DeSerialize<List<VolumeData>>(xmlData);

As I mentioned, I have no issue using these methods de-serializing other objects, or the properties within this class that is not a DateTime.

Thanks.

Upvotes: 1

Views: 1353

Answers (3)

mcw
mcw

Reputation: 3596

What does the date representation look like in the xml you're getting?

The following is working for me:

        string date1 = "04-20-2011";
        string date2 = "02-02-2011";

        VolumeData v1 = new VolumeData { date = DateTime.Parse(date1) };
        VolumeData v2 = new VolumeData { date = DateTime.Parse(date2) };

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(VolumeData));

        StringWriter w1 = new StringWriter();
        xmlSerializer.Serialize(w1, v1);
        string s1 = w1.ToString();

        StringWriter w2 = new StringWriter();
        xmlSerializer.Serialize(w2, v2);
        string s2 = w2.ToString();

        VolumeData v1a = (VolumeData)DeSerialize<VolumeData>(s1);
        VolumeData v2a = (VolumeData)DeSerialize<VolumeData>(s2);

but the xml contents for the date property (in s1) are:

<date>2011-04-20T00:00:00</date>

Upvotes: 0

NateTheGreat
NateTheGreat

Reputation: 2305

This page describes a similar problem: Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss'

You might be able to cheat a little bit and mark your date field with the [System.Xml.Serialization.XmlElementAttribute] listed on that other stackoverflow page.

Upvotes: 2

justin.lovell
justin.lovell

Reputation: 675

I would rather process through the XML via the Linq to XML and build up the tree that way.

Upvotes: 0

Related Questions