提问人:petros 提问时间:1/11/2016 最后编辑:petros 更新时间:10/30/2023 访问量:8899
C# 从 xml 反序列化 datetime
C# deserialize datetime from xml
问:
我必须反序列化 xml,日期如下所示:
<date>2015/10/16 00:00:00.000000000</date>
我的类包含以下字段:
[XmlAttribute("date")]
public DateTime StartDate { get; set; }
但我总是收到默认日期。是否可以解析这种格式的日期时间?
编辑: 当我将 XmlAttribute 更改为 XmlElement 时,出现异常:
There is an error in XML document
所以我认为 DateTime 可以解析这种格式。
答:
0赞
andreikashin
3/16/2018
#1
处理此问题的一种方法是使用 [System.Xml.Serialization.XmlIgnore] 修饰 DateTime 成员
这会告诉序列化程序根本不序列化或反序列化它。
然后,向类添加一个附加属性,例如 DateString。它可能被定义为
public string DateString {
set { ... }
get { ... }
}
然后,您可以在 get/set 逻辑中序列化和取消 DateString:
public string DateString {
set {
// parse value here - de-ser from your chosen format
// use constructor, eg, Timestamp= new System.DateTime(....);
// or use one of the static Parse() overloads of System.DateTime()
}
get {
return Timestamp.ToString("yyyy.MM.dd"); // serialize to whatever format you want.
}
}
在 get 和 set 中,您正在操作 Date 成员的值,但您正在使用自定义逻辑执行此操作。当然,序列化属性不一定是字符串,但这是一种简单的方法。您也可以使用 int 进行 ser/de-ser,例如 unix epoch
作者:Dino Chiesa
评论
[XmlElement]
DateTime
[XmlAttribute("date")]