gpt4 book ai didi

C# 从 xml 反序列化日期时间

转载 作者:行者123 更新时间:2023-11-30 12:57:21 26 4
gpt4 key购买 nike

我必须反序列化带有日期的 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 可以解析这种格式。

最佳答案

处理这个问题的一种方法是用 DateTime 成员装饰 [System.Xml.Serialization.XmlIgnore]

这告诉序列化器根本不序列化或反序列化它。

然后,向该类添加一个附加属性,例如称为 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 进行序列化/反序列化,例如 unix 纪元

来自 Dino Chiesa

关于C# 从 xml 反序列化日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com