Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

.net - XML Deserialization of a date with an empty value

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{...}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...