Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a DataType="time" field using XmlSerializer

Tags:

I'm getting an odd result when serializing a DateTime field using XmlSerializer.

I have the following class:

public class RecordExample
{
    [XmlElement("TheTime", DataType = "time")]
    public DateTime TheTime { get; set; }

    [XmlElement("TheDate", DataType = "date")]
    public DateTime TheDate { get; set; }

    public static bool Serialize(
        Stream stream, object obj, Type objType, Encoding encoding)
    {
        try
        {
            var settings = new XmlWriterSettings { Encoding = encoding };

            using (var writer = XmlWriter.Create(stream, settings))
            {
                var xmlSerializer = new XmlSerializer(objType);
                if (writer != null) xmlSerializer.Serialize(writer, obj);
            }

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}

When i call the use the XmlSerializer with the following testing code:

var obj = new RecordExample 
{ 
    TheDate = DateTime.Now.Date, 
    TheTime = new DateTime(0001, 1, 1, 12, 00, 00) 
};

var ms = new MemoryStream();

RecordExample.Serialize(ms, obj, typeof(RecordExample), Encoding.UTF8);
txtSource2.Text = Encoding.UTF8.GetString(ms.ToArray());

I get some strange results, here's the xml that is produced:

<?xml version="1.0" encoding="utf-8"?>
<RecordExample 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <TheTime>12:00:00.0000000+00:00</TheTime>
    <TheDate>2010-03-08</TheDate>
</RecordExample>

Any idea's how i can get the "TheTime" element to contain a time which looks more like this:

<TheTime>12:00:00.0Z</TheTime>

...as that's what i was expecting?

Thanks

Dave

like image 821
CraftyFella Avatar asked Mar 08 '10 15:03

CraftyFella


2 Answers

I've had different issues with this myself... however I was attempting to serialize a TimeSpan object. The solution was to have two properties, one that held the TimeSpan, and one that was a string representation of the TimeSpan which got Serialized. Here was the pattern:

[XmlIgnore]
public TimeSpan ScheduledTime
{
    get;
    set;
}

[XmlElement("ScheduledTime", DataType="duration")]
public string XmlScheduledTime
{
    get { return XmlConvert.ToString(ScheduledTime); }
    set { ScheduledTime = XmlConvert.ToTimeSpan(value); }
}

However, with this code, the time is printed out in the following format:

<ScheduledTime>PT23H30M</ScheduledTime>

The W3C definition of duration is here which explains it.

like image 195
Nick Avatar answered Sep 28 '22 07:09

Nick


take a look at this question Serializing DateTime to time without milliseconds and gmt

like image 37
IordanTanev Avatar answered Sep 28 '22 09:09

IordanTanev