获得深度嵌入的XML元素值

本文关键字:XML 元素 深度 | 更新日期: 2023-09-27 17:54:13

我正在尝试获取地址的纬度/经度,并且我正在使用dev.virtualearth.net上的XML提供程序。

XML输出如下:

<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>

我创建了一个XDocument,我试图获得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")
               };

但是纬度和经度值都是空的

我做错了吗?

获得深度嵌入的XML元素值

也应该使用嵌套元素的命名空间

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")
                   });