Extract data from xml in c# getting NullReference

87 views Asked by At

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

There are 2 answers

1
Umair M On BEST ANSWER

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.

0
Uwe Schmidt On

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.