Reputation: 327
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?
Upvotes: 1
Views: 938
Reputation: 6495
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.
Upvotes: 9
Reputation: 19604
The XML file in your sample returns some station
elements with no icao
descendant so sometimes station.Element("icao")
will return null.
Upvotes: 1
Reputation: 8966
Try something like this:
var stations = from station in xmlDoc.Elements("station")
select new
{
ICAO = station.Element("icao").Value,
};
Upvotes: 0
Reputation: 43074
That URL doesn't appear to be returning XML data, I suspect that's causing your node references to return nulls.
Upvotes: 0
Reputation: 26426
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.
Upvotes: 0