0

I am currently making my first steps in extracting data from an XML i get, where the following link provides the response I get: http://maps.google.com/maps/api/geocode/xml?address=AT,%20Wien

Now I try to get the latitude and logitude of the first element:

 string serviceUri = string.Format("http://maps.google.com/maps/api/geocode/xml?address=AT,", location);
        XmlDocument doc = new XmlDocument();
        XDocument X = XDocument.Load(serviceUri);

        var position = X.Element("GeoCodeResponse").Element("result");
        var position1= position.Element("geometry").Element("location");
        string latitude = position1.Element("lat").Value;
        string longitude = position1.Element("lng").Value;

But it seems I missunderstood something from that question which was also answered here: C# extracting data from XML

Please help me understand it a little bit further, br

Community
  • 1
  • 1
HalbeSuppe
  • 47
  • 5
  • 2
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –  Jun 17 '15 at 22:18
  • What line gets the null reference? – johnc Jun 17 '15 at 22:25

2 Answers2

1

Try using

var position = X.Root.Element("result");

if you debug your code in visual studio you will see that X.Element("GeoCodeResponse") returns null. And you are trying to use X.Element("") on null. You can also check null before accessing your root node.

Umair M
  • 8,566
  • 3
  • 33
  • 67
  • Could you please [edit] in an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/q/148272/274165), because they don't teach the solution. (This post was flagged by at least one user, presumably because they thought an answer without explanation should be deleted.) – Nathan Tuggy Jun 18 '15 at 01:08
1

The solution is simple.

If you're splitting the statements like

var root = X.Element("GeoCodeResponse");
var position = root.Element("result");

You will see, that the NPE is thrown by

var position = root.Element("result");

If you're looking in debugmode what 'root' contains. You will see, that 'root' is 'null'. So there is no element 'GeoCodeResponse'. It should be namend like 'GeocodeResponse' and you're solution works.

Uwe Schmidt
  • 71
  • 1
  • 7