0

Happily reading XML with

var q2 = from c in xmlDoc.Descendants("Ticket")
         select new
                { Responded_Date = (DateTime)c.Element("Responded_Date") }

However when the tag is

<Responded_Date xsi:nil="true" />

I get "String was not recognized as a valid DateTime". I don't wish to use the null coalescing operator but simply to take the null and insert into datatable

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
DingoCC
  • 159
  • 1
  • 2
  • 12

2 Answers2

1

Declare Responded_Date as a nullable datetime.

var q2 = from c in xmlDoc.Descendants("Ticket")
         select new { Responded_Date = (DateTime?)c.Element("Responded_Date") };

If the <Responded_Date> element is missing, a null value will be returned.

If it's an invalid date, you will get a FormatException - "String was not recognized as a valid DateTime.". <Responded_Date xsi:nil="true" /> will cause a FormatException.

jim31415
  • 8,588
  • 6
  • 43
  • 64
  • How do I declare the datetime nullable inside the select new statement? – DingoCC Mar 08 '11 at 04:32
  • I get this error inside the select. Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. – DingoCC Mar 08 '11 at 04:45
  • Modifed the code snippet to clarify where to put the DateTime?. – jim31415 Mar 09 '11 at 00:03
0

Linq to XML does not natively support xsi:nil, also see this msdn social link. As a workaround what you will have to do is manual checking and then either assign some default value for your date (i.e. DateTime.MaxValue) or use a class projection instead of an anonymous type and assign null to a nullable DateTime? property.

with anonymous type (Responded_Date of type DateTime :

 select new
          { 
            Responded_Date = c.Element("Responded_Date").Value!="" 
                             ? (DateTime)c.Element("Responded_Date")
                             : DateTime.MaxValue
          }

with custom class projection (Responded_Date of type DateTime?):

 select new MyFoo()
          { 
            Responded_Date = c.Element("Responded_Date").Value!="" 
                             ? (DateTime)c.Element("Responded_Date")
                             : null
          }
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335