XmlSerializer: The string '' is not a valid AllXsd value

前端 未结 5 1588
独厮守ぢ
独厮守ぢ 2020-12-20 10:52

I\'m getting this message,\"The string \'7/22/2006 12:00:00 AM\' is not a valid AllXsd value.\", when deserializing an XML, the element contains a date, this is the property

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-20 11:49

    I realize that this is an old question, but I had this issue today and I found a workaround using properties and casting.

    private string _date; // Private variable to store XML string
    
    // Property that exposes date. Specifying the type forces
    // the serializer to return the value as a string.
    [XmlElement("date", Type = typeof(string))]
    public object Date {
        // Return a DateTime object
        get
        {
            return
                !string.IsNullOrEmpty(_date) ? 
                (DateTime?) Convert.ToDateTime(_date) : 
                null;
        }
        set { _date = (string)value; } 
    }
    

    Now, whenever you need to refer to the date, you simply call:

    var foo = (DateTime?)Bar.Date
    

    It's been working fine for me since. If you don't mind adding the extra cast in your code, you can do it this way as well!

    Edit: Due to Dirk's comment, I decided to revisit my implementation in a seperate branch. Rather than using an object class, which is prone to runtime compiler errors, I return the value as a string.

    [XmlElement("date")] 
    public string Date;
    

    Which makes the declaration much simpler. But when attempting to read from the variable you now need to provide null checks.

    var foo = string.IsNullOrEmpty(Date) ? Convert.ToDateTime(Date) : (DateTime?) null
    

    It works the exact same way as the previous implementation, except the casting and null checks occur at a different location. I want to be able to write my model and then forget about it, so I still prefer my implementation instead.

    On another note, I added a correction to the cast before the edit: DateTime should be DateTime?.

提交回复
热议问题