Raj123
Raj123

Reputation: 981

Reading specific values from XML response generated by google maps api

I am trying to get address from the XML file returned by google map api (by giving lat/lng as parameters). I am using the following code.

XDocument doc = XDocument.Load("uri");
var city = doc.Descendants("result").Where(s => s.Descendants("type").FirstOrDefault().Value == "locality");

Then I am reading for a specific descendant

address = Convert.ToString(city.Descendants("formatted_address").First().Value);

which I am trying to show on a map. All works fine for the first time(when I get the lat/lng values based on my IPAddress) but when the user double clicks on the map (am supposed to get the location of the click) the program is crashing. Works fine sometimes. I checked and its because in the xml file returned, sometimes there is no node type "locality" under "result". I wrote if and else if statements for this case but the debugger is still going inside the if loop and later showing the error "Sequence contains no elements". Doing this in a WPF application.

For ex : The only result nodes returned for 27/14 are type country & administrative_area_level_1.

Upvotes: 1

Views: 515

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501053

You haven't shown us the XML involved, but I strongly suspect the problem is that you're not specifying the namespace. You probably want something like:

XNamespace ns = "some namespace URI";
XDocument doc = XDocument.Load("uri");

var city = doc.Descendants(ns + "result")
              .Where(s => s.Descendants(ns + "type")
                           .FirstOrDefault().Value == "locality");

Of course there may be multiple namespaces involved - be aware of namespace inheritance due to xmlns="..." as well.

I would personally suggest using a simple cast from XElement to string instead of using the Value property - that way if FirstOrDefault() returns null, the result of the cast is null as well.

(It's not clear that your query really makes much sense, to be honest.)

Upvotes: 2

Related Questions