c# XML反序列化时间字符串列表到列表DateTime对象



我很难理解这一点。我从API调用返回一堆xml(我没有控制)。数据看起来像这样,但是有更多的条目。

`<time>10:00:00</time>
 <go>true</go>
 <time>10:30:00</time>
 <go>false</go>
`

我可以很好地反序列化成一个列表两个字符串列表List<string> time and list<string> go

但是,我确实需要将该时间反序列化为datetime对象。现在我有以下工作,但只针对单个实例,而不是一个列表。毫无疑问,我在getter和setter上遇到了麻烦

[XmlIgnore]
public List<DateTime> DoNotSerialize { get; set; }
[XmlElement("time")]
public List<string> time
{
     get { return DoNotSerialize.ToString("HH:MM:SS") }
     set { DoNotSerialize = DateTime.Parse(value); }
}

试试:

[XmlIgnore]
public List<DateTime> DoNotSerialize { get; set; }
[XmlElement("time")]        
public List<string> time
{
    get { return DoNotSerialize.Select(item => item.ToString("yyyy-MM-dd")).ToList(); }
    set { DoNotSerialize = value.Select(item => DateTime.Parse(item)).ToList(); }
}

(几天前我遇到过类似的问题,但是是序列化而不是反序列化。如果你感兴趣,看看我之前的问题…)

最新更新