【问题标题】:C# deserialize datetime from xmlC#从xml反序列化日期时间
【发布时间】:2016-04-16 00:07:13
【问题描述】:

我必须用如下所示的日期反序列化 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 可以解析这种格式。

【问题讨论】:

标签: c# xml-parsing


【解决方案1】:

处理此问题的一种方法是使用 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 进行 ser/de-ser,例如使用 unix 纪元

迪诺·基耶萨

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    相关资源
    最近更新 更多