c# - 获取深度嵌入的 XML 元素值

标签 c# asp.net xml xml-parsing

我正在尝试获取地址的纬度/经度,并且我正在使用 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")
               };

但我只是得到纬度和经度值的空值。

我做错了吗?

最佳答案

您也应该对嵌套元素使用命名空间。

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

关于c# - 获取深度嵌入的 XML 元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30715557/

相关文章:

javascript - 无法在Javascript函数中访问span标签的innerHTML

asp.net - 用于集成测试 asp.net 应用程序的不同资源文件

ruby - 如何使用 Nokogiri 浏览 XML 文件?

java - 比较两个 XML 实例的变化

c# - 在 Debug模式下发布,但编译器会删除 #if debug 中的代码

c# - 将位图 header 添加到字节数组,然后创建位图文件

c# - 远程MySQL访问耗时较长

c# - DDD 中的多对多关系

c# - 在 ASP.NET 中,您如何才能返回 "reset"并返回到原始状态,即回发前?

java - 使用 JAXB 解码 xml 文件时使用什么策略?