2010-11-13 50 views
2

我從WebClient String(xml)得到答案。如何用Linq提取一些屬性,例如lat和lng?linq到XML字符串

<?xml version="1.0" encoding="UTF-8"?> 
<GeocodeResponse> 
<status>OK</status> 
<result> 
    <type>route</type> 
    <formatted_address>Prince Michael St, Belgrade, Serbia</formatted_address> 
    <address_component> 
    <long_name>Prince Michael St</long_name> 
    <short_name>Prince Michael St</short_name> 
    <type>route</type> 
    </address_component> 
    <address_component> 
    <long_name>Stari Grad</long_name> 
    <short_name>Stari Grad</short_name> 
    <type>sublocality</type> 
    <type>political</type> 
    </address_component> 
    <address_component> 
    <long_name>Belgrade</long_name> 
    <short_name>Belgrade</short_name> 
    <type>locality</type> 
    <type>political</type> 
    </address_component> 
    <address_component> 
    <long_name>City of Belgrade</long_name> 
    <short_name>City of Belgrade</short_name> 
    <type>administrative_area_level_2</type> 
    <type>political</type> 
    </address_component> 
    <address_component> 
    <long_name>Central Serbia</long_name> 
    <short_name>Central Serbia</short_name> 
    <type>administrative_area_level_1</type> 
    <type>political</type> 
    </address_component> 
    <address_component> 
    <long_name>Serbia</long_name> 
    <short_name>RS</short_name> 
    <type>country</type> 
    <type>political</type> 
    </address_component> 
    <geometry> 
    <location> 
    <lat>44.8157361</lat> 
    <lng>20.4593997</lng> 
    </location> 
    <location_type>GEOMETRIC_CENTER</location_type> 
    <viewport> 
    <southwest> 
    <lat>44.8122468</lat> 
    <lng>20.4564820</lng> 
    </southwest> 
    <northeast> 
    <lat>44.8185421</lat> 
    <lng>20.4627772</lng> 
    </northeast> 
    </viewport> 
    <bounds> 
    <southwest> 
    <lat>44.8150440</lat> 
    <lng>20.4593895</lng> 
    </southwest> 
    <northeast> 
    <lat>44.8157449</lat> 
    <lng>20.4598697</lng> 
    </northeast> 
    </bounds> 
    </geometry> 
</result> 
</GeocodeResponse> 

回答

3

您可以使用XDocument.Parse方法獲取XDocument對象進行字符串。您可以像使用任何XDocument一樣將LINQ應用於XML。舉例來說,你可以得到的文檔中的所有元素<lat>有:

XDocument.Parse(xmlString).Descendants("lat") 

您使用的確切查詢取決於你想從文檔中提取什麼。

+0

解決這個,感謝一個! – Jelena 2010-11-13 00:17:24