开发者

Using Linq to Get Lat/Lon from Bing Maps REST Service

I'm calling the Bing Maps Service to return some XML here开发者_JAVA百科:

http://dev.virtualearth.net/REST/v1/Locations/Encoded_Address?o=xml&key=Maps_Key

For the life of me, I can't seem to get the Longitude and Latitude using Linq! It always returns null. Here's the code I'm using (I've used Atlanta, GA as an example):

xml = XElement.Load(url); // url is as above
var locations = from l in xml.Descendants( "Location" )
                        select l;
// Output to Test    
foreach(var location in xml.Descendants("Location")){
  // We NEVER get in here.
  Console.WriteLine( "Lat: "  + location.Descendants("Latitude").First().Value );
  Console.WriteLine( "Long: " + location.Descendants("Longitude").First().Value);
  Console.ReadLine();
}

I've also tried adding a namespace:

XNamespace xn = "http://schemas.microsoft.com/search/local/ws/rest/v1";
xml.Descendants(xn + "Location"))

But NO go. What am I doing wrong???

Here's the relevant XML fragment (only relevant parts are here)

<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
  <ResourceSets>
    <ResourceSet>
      <EstimatedTotal>1</EstimatedTotal>
      <Resources>
        <Location>
          <Name>Atlanta, GA</Name>
          <Point>
            <Latitude>33.748315</Latitude>
            <Longitude>-84.39111</Longitude>
          </Point>
          <!-- other stuff here -->
        </Location>
      </Resources>
    </ResourceSet>
  </ResourceSets>
</Response>


You'll have to include namespace in all places as shown below.

// Output to Test    
foreach(var location in xml.Descendants(xn +"Location")){
  // NOW WE GET IN HERE.
  Console.WriteLine( "Lat: "  + location.Descendants(xn +"Latitude").First().Value );
  Console.WriteLine( "Long: " + location.Descendants(xn + "Longitude").First().Value);
  Console.ReadLine();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜