Getting deeply embedded XML element values

80 views Asked by At

I'm trying to get the latitude/longitude of an address, and I'm using the XML provider on dev.virtualearth.net.

The XML comes out like this:

<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
   <StatusCode>200</StatusCode>
   <StatusDescription>OK</StatusDescription>
   <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
   <ResourceSets>
       <ResourceSet>
           <EstimatedTotal>2</EstimatedTotal>
       <Resources>
       <Location>
           <Name>350 Avenue V, New York, NY 11223</Name>
           <Point>
               <Latitude>40.595024898648262</Latitude>
               <Longitude>-73.969506248831749</Longitude>
           </Point>

I created an XDocument and I'm trying to get the Latitude and Longitude values under Point

XDocument doc = GetDoc();

XNamespace xmlns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

var latlong = from c in docDescendants(xmlns + "Point")
               select new
               {
                   latitude = c.Element("Latitude"),
                   longitude = c.Element("Longitude")
               };

But I'm just getting null for the latitude and longitude values.

Am I doing this wrong?

1

There are 1 answers

0
Hamlet Hakobyan On BEST ANSWER

You should use namespace with nested elements as well.

string xmlString = 
@"
<Response xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
    xmlns=""http://schemas.microsoft.com/search/local/ws/rest/v1"">
   <StatusCode>200</StatusCode>
   <StatusDescription>OK</StatusDescription>
   <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
   <ResourceSets>
       <ResourceSet>
           <EstimatedTotal>2</EstimatedTotal>
       <Resources>
       <Location>
           <Name>350 Avenue V, New York, NY 11223</Name>
           <Point>
               <Latitude>40.595024898648262</Latitude>
               <Longitude>-73.969506248831749</Longitude>
           </Point>
        </Location>
        </Resources>
        </ResourceSet>
    </ResourceSets>
</Response>
";
var doc = XDocument.Parse(xmlString);
XNamespace ns = "http://schemas.microsoft.com/search/local/ws/rest/v1";
var positions = doc.Descendants(ns + "Point")
       .Select(p =>
               new {
                      Latitude = (double)p.Element(ns + "Latitude"),
                      Longitude = (double)p.Element(ns + "Longitude")
                   });