c# - 获取xml文件中标签之间的数据

标签 c# xml xml-parsing

我想获取 <lat> 之间的数据和 <lng>以下 XML 中的标记:

<viewport>
 <southwest>
  <lat>41.7450495</lat>
  <lng>-87.8859170</lng>
 </southwest>
</viewport>

这是更大的 XML 的一部分:

<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>Chicago, IL, USA</formatted_address>
  <address_component>
   <long_name>Chicago</long_name>
   <short_name>Chicago</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Cook</long_name>
   <short_name>Cook</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Illinois</long_name>
   <short_name>IL</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>United States</long_name>
   <short_name>US</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>41.8781136</lat>
    <lng>-87.6297982</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>41.7450495</lat>
     <lng>-87.8859170</lng>
    </southwest>
    <northeast>
     <lat>42.0109012</lat>
     <lng>-87.3736794</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>41.6443350</lat>
     <lng>-87.9402669</lng>
    </southwest>
    <northeast>
     <lat>42.0231310</lat>
     <lng>-87.5236609</lng>
    </northeast>
   </bounds>
  </geometry>
 </result>
</GeocodeResponse>

现在,我正在尝试使用这段代码来解析它:

string url = "http://maps.googleapis.com/maps/api/geocode/xml?address="+address+"&sensor=false";
WebClient client = new WebClient();

string result = client.DownloadString(url);

var element = XElement.Parse(result);
var lat = (double)element.Element("lat");
var lng = (double)element.Element("lng");

但它不起作用,元素是 null .我该怎么做?

最佳答案

不要使用正则表达式,解析它。这使用 LINQ to XML。

这应该适合你:

var doc = XDocument.Parse(result);
var sw = doc.Descendants("viewport").Elements("southwest").SingleOrDefault();
if (sw != null)
{
    var lat = (double)sw.Element("lat");
    var lng = (double)sw.Element("lng");
    // do stuff
}

关于c# - 获取xml文件中标签之间的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6260941/

相关文章:

c# - 在 Enum 中搜索字符串并返回 Enum

c# - 简单的 C# OOP 继承查询

java - 获取类属性名称、其类型以及如果是集合则获取集合的泛型类型

xml - Golang : Read single XML document from net.康恩

java - 一个 Web 应用程序中特定的多个 SAXParserFactory 实现

c# - 将 .Net 对象序列化为 json,使用 xml 属性控制

c# - 如何使用 EntityFramework 实现通用 MVC Web Controller 和用于 CRUD 操作的通用 View

android - 在绑定(bind)适配器上传递 View ID?

php - PHP 中的 XSD 架构 1.1 验证

xml-parsing - 使用 (xpath) 条件解码 XML