将日期时间字符串解析为 Xml 序列化中的日期时间

3 c# xml serialization datetime

我正在检索日期时间字符串“2015-07-16T07:40:35Z”。

<?xml version="1.0" encoding="UTF-8"?>
<people type="array">
   <person>
      <last-name>lastName</last-name>
      <first-name>firstName</first-name>
      <id type="integer">123</id>
      <last-changed-on type="date">2014-11-21T15:04:53Z</last-changed-on>
   </person>
</people>
Run Code Online (Sandbox Code Playgroud)

我搜索了这个问题并发现了类似下面的内容。

[XmlIgnore]
public DateTime Start { get; set; }

[XmlElement("start")]
public string StartDateString
{
    get { return this.Start.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"); }
    set { this.Start = DateTime.Parse(value); }
}
Run Code Online (Sandbox Code Playgroud)

我想将该 XmlElement 反序列化为对象的 Datetime 属性。之后,当我序列化该对象时,我想创建一个格式为“2015-07-16T07:40:35Z”的日期时间字符串。那么我将如何更改此问题的属性的获取/设置块。

ste*_*351 7

看起来您正在处理的格式是标准 XML DateTime 格式。因此,在这种情况下,您不需要代理字符串属性来处理它,您可以使用 的内置功能XmlSerializer并指定dateTime相关的数据类型XmlElement。更新:dateTime如果元素为空(即使与 结合使用isNullable),则指定 不起作用,这是一种将字符串手动转换为 的方法DateTime

例如..

[XmlRoot("person")]
public class Person
{
    [XmlElement("last-name")]
    public string LastName { get; set; }
    [XmlElement("first-name")]
    public string FirstName { get; set; }
    [XmlElement("id")]
    public int Id { get; set; }
    [XmlElement(ElementName = "last-changed-on")]
    public XmlDateTime LastChangedOn { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

编辑:听起来您的 XmlLastChangedOn可能为空或丢失。在这种情况下,您可以实现一个自定义类来处理转换并保持Person类干净。我添加了隐式转换,因此您可以将该属性视为DateTime. 上面稍微改变一下,用XmlDateTimehas 代替DateTime

[DebuggerDisplay("{Value}")]
public class XmlDateTime : IXmlSerializable
{
    public DateTime Value { get; set; }
    public bool HasValue { get { return Value != DateTime.MinValue; } }
    private const string XML_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        if (reader.IsEmptyElement)
        {
            reader.ReadStartElement();
            return;
        }

        string someDate = reader.ReadInnerXml();
        if (String.IsNullOrWhiteSpace(someDate) == false)
        {
            Value = XmlConvert.ToDateTime(someDate, XML_DATE_FORMAT);
        }
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        if (Value == DateTime.MinValue)
            return;

        writer.WriteRaw(XmlConvert.ToString(Value, XML_DATE_FORMAT));
    }

    public static implicit operator DateTime(XmlDateTime custom)
    {
        return custom.Value;
    }

    public static implicit operator XmlDateTime(DateTime custom)
    {
        return new XmlDateTime() { Value = custom };
    }
}
Run Code Online (Sandbox Code Playgroud)