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

问题描述 投票:0回答:1

我必须反序列化带有日期的 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个回答
0
投票

处理这个问题的一种方法是用 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 纪元

来自 Dino Chiesa

© www.soinside.com 2019 - 2024. All rights reserved.