我收到从一个供应商,它有一些空日期这样的XML文件:
< UpdatedOn />
< DeletedOn />
做一个定期的反序列化失败有:
内部异常信息:System.FormatException:字符串未被识别为有效的DateTime
任何想法如何处理?
我的字段已经标记为默认的的DateTime
:
[System.Xml.Serialization.XmlElementAttribute(数据类型=约会)
[System.ComponentModel.DefaultValueAttribute(typeof运算(System.DateTime的),1901年1月1日)]
公众的System.DateTime UpdateOn {...}
解决方案
我假设的XML实际上是像< UpdatedOn />
/ < DeletedOn />
?即空元素。
在涉及非标准格式,一种技巧,作品是介绍自己的垫片属性:
[Serializable接口]
公共类Foo {
[XmlIgnore]
公开日期时间吧{获得;组; }
[可浏览(假),EditorBrowsable(EditorBrowsableState.Never)
[的XmlElement(酒吧)
公共字符串BarTransport {
得到 {
返回酒吧== DateTime.MinValue? :XmlConvert.ToString(条);
}
组 {
酒吧= string.IsNullOrEmpty(价值)? DateTime.MinValue
:XmlConvert.ToDateTime(值);
}
}
}
在这里, Foo.Bar
属性(实际的DateTime
)序列化过程中不使用;但有特殊规定 - 相反, Foo.BarTransport
属性下的酒吧
元素序列化。您可以使用您想要把一个空白/默认任何其他值替换 DateTime.MinValue
。
请注意,如果您不希望发送酒吧
元素可言,你可以写一个公共BOOL ShouldSerializeBarTransport()
,其中的XmlSerializer
将检查 - 如果返回假
,将不会被写入
I'm getting a xml file from one vendor that has some "empty" dates like this:
<UpdatedOn/>
<DeletedOn/>
By doing a regular deserialization it fails with:
Inner Exception: System.FormatException: String was not recognized as a valid DateTime.
Any ideas how to deal with this ?
My fields are already marked for a default DateTime
:
[System.Xml.Serialization.XmlElementAttribute(DataType="date")]
[System.ComponentModel.DefaultValueAttribute(typeof(System.DateTime), "1901-01-01")]
public System.DateTime UpdateOn{...}
解决方案
I'm assuming that the xml is actually something like <UpdatedOn/>
/ <DeletedOn/>
? i.e. empty elements.
When non-standard formats are involved, one trick that works is to introduce your own shim property:
[Serializable]
public class Foo {
[XmlIgnore]
public DateTime Bar { get; set; }
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[XmlElement("Bar")]
public string BarTransport {
get {
return Bar == DateTime.MinValue ? "" : XmlConvert.ToString(Bar);
}
set {
Bar = string.IsNullOrEmpty(value) ? DateTime.MinValue
: XmlConvert.ToDateTime(value);
}
}
}
Here, the Foo.Bar
property (the actual DateTime
) isn't used during serialization; instead, the Foo.BarTransport
property is serialized under the Bar
element - but with special rules. You can replace DateTime.MinValue
with any other value that you want to treat as the blank/default.
Note that if you don't want to send the Bar
element at all, you can write a public bool ShouldSerializeBarTransport()
, which XmlSerializer
will check - if you return false
, it won't get written.