XML Deserialization of a date with an empty value

后端 未结 2 429
一个人的身影
一个人的身影 2020-12-16 04:12

I\'m getting a xml file from one vendor that has some \"empty\" dates like this:



By doing a regular d

相关标签:
2条回答
  • 2020-12-16 04:38

    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.

    0 讨论(0)
  • 2020-12-16 04:38

    Try to change the <UpdatedOn/> to <UpdatedOn xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" /> and you can deserialize the XML.

    0 讨论(0)
提交回复
热议问题