如何反序列化DateTime对象列表?

时间:2009-08-10 21:14:46

标签: c# .net xml-serialization

如果我有以下XML段:

<Times>
  <Time>1/1/1900 12:00 AM</Time>
  <Time>1/1/1900 6:00 AM</Time>
</Times>

当反序列化发生时,相应的属性应该是什么样的,将上述XML接受到DateTime对象列表中?

这可以将XML段反序列化为string个对象列表:

[XmlArray("Times")]
[XmlArrayItem("Time", typeof(string))]
public List<string> Times { get; set; }

但是当我使用DateTime作为类型而不是字符串时(对于List类型和XmlArrayItem类型),我收到以下错误:

The string '1/1/1900 12:00 AM' is not a valid AllXsd value.

谢谢!

3 个答案:

答案 0 :(得分:5)

使用DateTime,我希望问题的很大一部分是xml的格式错误;这不是日期的xsd标准......你能影响xml吗?否则,你可能不得不坚持使用字符串并在之后处理它。

更多标准xml将是:

<Times>
  <Time>1900-01-01T00:00:00</Time>
  <Time>1900-01-01T06:00:00</Time>
</Times>

例如:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Data
{

    [XmlArray("Times")]
    [XmlArrayItem("Time")]
    public List<DateTime> Times { get; set; }

    static void Main()
    {
        XmlReader xr = XmlReader.Create(new StringReader(@"<Data><Times>
  <Time>1900-01-01T00:00:00</Time>
  <Time>1900-01-01T06:00:00</Time>
</Times></Data>"));
        XmlSerializer ser = new XmlSerializer(typeof(Data));
        Data data = (Data) ser.Deserialize(xr);
        // use data
    }
}

答案 1 :(得分:3)

最简单的方法是创建一个序列化而不是Times属性的新属性,并处理格式化:

    [XmlIgnore]
    public IList<DateTime> Times { get; set; }

    [XmlArray("Times")]
    [XmlArrayItem("Time")]
    public string[] TimesFormatted
    {
        get
        {
            if (this.Times != null)
                return this.Times.Select((dt) => dt.ToString("MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture)).ToArray();
            else
                return null;
        }
        set
        {
            if (value == null)
                this.Times = new List<DateTime>();
            else
                this.Times = value.Select((s) => DateTime.ParseExact(s, "MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture)).ToList();
        }
    }

答案 2 :(得分:0)

看一下msdn文章: http://msdn.microsoft.com/en-us/library/ms950721.aspx

它表明DateTime对象应该标记为: [System.Xml.Serialization.XmlElementAttribute( “出版物日期”, 数据类型= “日期”)]
    public System.DateTime publicationdate;

相关问题