locked
Xml deserialization of a Nullable DateTime object RRS feed

  • Question

  • Morning, we've had this a lot but the answers I've found do not appear to work.

     

    C# 3.0, .Net 3.5, XML Serialization into a nullable DateTime property does not work with an empty string.  The exception is thrown before the internals of the property, when the XmlSerializer attempts to use DateTime.ParseExact (when I use a DataType="date" value) and just complains that it is not a valid DateTime format when I do not.

    A few of the various combinations of signature that I have used are below but am I fundamentally wrong that empty strings should be classed as null values?  I bet at the end of this the conclusion will be: "if you have a value then pass a populated element in the xml, if you don't then don't pass that element at all" or "if you have no value you can still send the element so long as it has the xsi:nil attribute" .

    A few combinations:

    [XmlElement("foo")]

    DateTime Foo {get; set;}

     

    [XmlElement("foo")]

    DateTime? Foo {get; set;}

     

    [XmlElement("foo", DataTime="date")] // yes I just want the date part

    DateTime? Foo {get; set;}

     

    [XmlElement("foo", IsNullable=true)] // I believe Bet that this only makes a difference serialising to xml not from xml

    DateTime Foo {get; set;}

     

    <CutMoreCombinations />

     

    The XML I'm sending is "<foo />"

     

    Thanks

    Andy

     

     

    • Edited by Andrew-Murphy Thursday, September 23, 2010 7:38 AM Forgot a closing quote mark
    • Moved by SamAgain Monday, September 27, 2010 2:27 AM xml serialization related (From:.NET Base Class Library)
    Thursday, September 23, 2010 7:34 AM

Answers

  • Hi Nathan, thanks for your response but don't worry about it.  It appears that if we add the xsi namespace declaration into the xml then it all works a treat.

     

     

     

    <Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    .....

     

    We've wasted hours on this and didn't spot it.  Oh well.

    Monday, October 4, 2010 2:09 PM

All replies

  • Where are you getting the xml?

    The XmlSerializer will treat the absence of the element or xsi:nil=true as null, but an empty tag will have the value the empty string in which it will need to try to interpret that as a Nullable<DateTime>.

    Monday, September 27, 2010 11:12 PM
    Moderator
  • Hi Nathan, thanks for your response but don't worry about it.  It appears that if we add the xsi namespace declaration into the xml then it all works a treat.

     

     

     

    <Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    .....

     

    We've wasted hours on this and didn't spot it.  Oh well.

    Monday, October 4, 2010 2:09 PM