【发布时间】:2011-06-07 05:27:14
【问题描述】:
我想在以下 XML 中获取 <lat> 和 <lng> 标记之间的数据:
<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。我该怎么做?
【问题讨论】:
-
为什么要使用正则表达式来读取格式良好的 XML?
-
您确定不想要更多关于如何解析 xml 文件的内容吗? stackoverflow.com/questions/55828/… 之类的东西?
-
@Gabi: bobince 真的很棒! :) @karthik:您无法使用正则表达式解析 [X]HTML。因为正则表达式无法解析 HTML。正则表达式不是可用于正确解析 HTML 的工具。您是否尝试过使用 XML 解析器?
-
@naveen。肯定的正则表达式(由于是规则的,因此是有限自动机的产物)不完整,因此不易于解析整个 XML 文件。然而,如果您只想在两个众所周知的标签之间摘录一些值,无论它们出现在哪里,正则表达式肯定会成功。显然你应该用 XML 解析器来解析 XML,但是 OP 的问题是合法的。
标签: c# xml xml-parsing