OrElse
OrElse

Reputation: 9969

Simple XML parsing throws Object reference error

How can i parse the following XML File?

<Website.com xmlns="">
  <Matc>
    <Id>1</Id>
    <Date>2013-11-27T18:00:00+01:00</Date>
    <Home>Moscow</Home>
  </Matc>
  <Matc>
    <Id>2</Id>
  </Matc>
</Website.com>

I tried the following code but it throws that Object reference not set to an instance of an object error since [Date] and Home are missing at the second part of the XML file.

 Dim ns As XNamespace = ""
 Dim matcFromXml = From m In xDoc.Descendants("Matc") Select New With { _
   .Id = IIf(m.Element(ns + "Id") Is Nothing, 0, m.Descendants(ns + "Id").FirstOrDefault().Value), _
   .[Date] = IIf(m.Element(ns + "Date") Is Nothing, DateTime.Now, UtcToDateTime(m.Descendants(ns + "Date").FirstOrDefault().Value)), _
   .Home = IIf(m.Element(ns + "Home") Is Nothing, "", m.Descendants(ns + "Home").FirstOrDefault().Value)}

How can i fix that? What am i doing wrong here?

Upvotes: 0

Views: 87

Answers (1)

Zev Spitz
Zev Spitz

Reputation: 15357

It is highly recommended to cast an XElement to Integer or DateTime?, instead of reading the Value property, for precisely this reason. Also, consider using the If coalescing operator.

Dim matcFromXml = From m In xDoc.Descendants("Matc") Select New With { _
    .Id = CInt(m.Descendants(ns + "Id").FirstOrDefault()),
    .[Date] = If(CType(m.Descendants(ns + "Date").FirstOrDefault(), Date?), DateTime.Now),
    .Home = If(CStr(m.Descendants(ns + "Home").FirstOrDefault()),"")}

If there is no Id element, then using plain CInt for the Id will cause an error. Instead, use If and CType:

    .Id = If(CType(m.Descendants(ns + "Id").FirstOrDefault(),Integer?),0),

Upvotes: 1

Related Questions