在 C# 中将 XML 空日期反序列化为 DateTime

Joh*_*ohn 4 c# xml serialization datetime

我有以下 XML 需要反序列化为 C# 对象。除了有时为空的日期元素外,所有元素都有效。

<?xml version="1.0" encoding="utf-8" ?>
<Output xmlns:b="http://webservices.mycompany.com/Order/17.2.0">
    <b:RequestedCompletionDate>
      <State>Modified</State>
      <Action>DateSpecified</Action>
      <Date></Date>
    </b:RequestedCompletionDate>
</Output>
Run Code Online (Sandbox Code Playgroud)

模型类定义为:

[System.Xml.Serialization.XmlType(Namespace = "http://webservices.mycompany.com/Order/17.2.0", AnonymousType = true)]
[System.Xml.Serialization.XmlRoot(Namespace = "http://webservices.mycompany.com/Order/17.2.0", IsNullable = false)]
public partial class RequestedCompletionDate
{

    private string stateField;

    private string actionField;

    private DateTime? dateField;

    /// <remarks/>

    [System.Xml.Serialization.XmlElement(Namespace = "http://webservices.mycompany.com/Framework/17.2.0")]
    public string State
    {
        get
        {
            return this.stateField;
        }
        set
        {
            this.stateField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElement(Namespace = "http://webservices.mycompany.com/Framework/17.2.0")]
    public string Action
    {
        get
        {
            return this.actionField;
        }
        set
        {
            this.actionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElement(Namespace = "http://webservices.mycompany.com/Framework/17.2.0")]
    public DateTime? Date
    {
        get
        {
            return this.dateField;
        }
        set
        {

            this.dateField = value;


        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的例外是:

“字符串 '' 不是有效的 AllXsd 值。”

它不喜欢将空日期值传递给 DateTime 属性。

当日期值为空时,如何反序列化为 DateTime 属性?

JLR*_*she 5

在 XML 中表示空值的方法是使用xsi:nil属性:

<Output xmlns:b="http://webservices.mycompany.com/Order/17.2.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <b:RequestedCompletionDate>
      <State>Modified</State>
      <Action>DateSpecified</Action>
      <Date xsi:nil="true"></Date>
    </b:RequestedCompletionDate>
</Output>
Run Code Online (Sandbox Code Playgroud)

如果您的输入没有,那么您可以将其反序列化为字符串并在非序列化属性中处理转换:

[XmlIgnore]
public DateTime? Date
{
    get
    {
        DateTime dt;
        if(DateTime.TryParse(SerialDate, out dt))
        {
            return dt;
        }

        return null;
    }
    set
    {
        SerialDate = (value == null) 
            ? (string)null 
            : value.Value.ToString("yyyy-MM-ddTHH:mm:ss");
    }
}

[System.Xml.Serialization.XmlElement("Date", Namespace = "http://webservices.mycompany.com/Framework/17.2.0")]
public string SerialDate { get; set; }
Run Code Online (Sandbox Code Playgroud)