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

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you please edit in an explanation of why this code answers the question? Code-only answers are discouraged, 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.)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.