使用XmlSerializer序列化DateTime字段时,我得到一个奇怪的结果。

我有以下类(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;
        }
    }
}

当我通过以下测试代码调用XmlSerializer时:
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());

我得到一些奇怪的结果,这是生成的xml:
<?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>

任何想法是如何使“TheTime”元素包含一个看起来更像这样的时间的:
<TheTime>12:00:00.0Z</TheTime>

...因为那是我所期望的?

谢谢

戴夫

最佳答案

看看这个问题Serializing DateTime to time without milliseconds and gmt

10-08 19:41