tags:

views:

189

answers:

5

I'm getting the NRE error that says: "Object reference not set to an instance of an object."

From the following code:

  select new
                  {
                      ICAO = station.Element("icao").Value,
                  };

The entire script is:

XDocument xmlDoc = XDocument.Load(@"http://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?query=94107");

    var stations = from station in xmlDoc.Descendants("station")
                  select new
                  {
                      ICAO = station.Element("icao").Value,
                  };
    lblXml.Text = "";
    foreach (var station in stations)
    {
        lblXml.Text = lblXml.Text + "ICAO: " + station.ICAO + "<br />";
    }

    if (lblXml.Text == "")
        lblXml.Text = "No Results.";
    }

I don't understand why it isn't creating the station object and setting the ICAO value. Any ideas/tips for future XML and C# reference?

A: 

I don't think that xmlDoc.Descendants("station") is returning what you are expecting. You should examine the results here. This is why station.Element("icao") is returning null.

Keltex
A: 

That URL doesn't appear to be returning XML data, I suspect that's causing your node references to return nulls.

Lazarus
A: 

Try something like this:

var stations = from station in xmlDoc.Elements("station")
select new
{
    ICAO = station.Element("icao").Value,
};
Tim S. Van Haren
+9  A: 

It appears that only the airport stations have the icao element. This should work for you:

var stations = from airport in xmlDoc.Descendants("airport")
               from station in airport.Elements("station")
               select new
               {
                   ICAO = station.Element("icao").Value,
               };

You could instead add a where condition to get around the exception:

var stations = from station in xmlDoc.Descendants("station")
               where station.Element("icao") != null
               select new
               {
                   ICAO = station.Element("icao").Value,
               };

Also, you can pull a value like this to prevent an exception, though it will return numerous null records you may or may not want:

ICAO = (string)station.Element("icao")

You can do that for various other types, not only for strings.

Ryan Versaw
Not to mention protecting against station.Element("icao") being null with either an extension method or a where clause.
sixlettervariables
The second route is probably better, since you're not imposing an artificial business rule that may or may not be true.
GalacticCowboy
Yeah, a combination of both may be the ideal situation.
Ryan Versaw
+1  A: 

The XML file in your sample returns some station elements with no icao descendant so sometimes station.Element("icao") will return null.

VVS