我有以下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>
模型类定义为:
[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;
}
}
}
我得到的例外是:
&#34;字符串&#39;&#39;不是有效的AllXsd值。&#34;
它不像将null日期值传递给DateTime属性。
如果日期值为空,我如何反序列化为DateTime属性?
答案 0 :(得分:1)
在XML中表示空值的方法是使用xsi:nil
。
如果您的输入没有,那么将其反序列化为字符串并在非序列化属性中处理转换:
[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; }