2016-03-03 47 views
0

我有一個的XDocument(粘貼以下)我怎樣才能獲得市,州從我的XDocument

我如何可以查詢它來獲取城市和國家出來的嗎? ex。我可能想通過類型進行查詢,其中類型值是「地方」

<GeocodeResponse> 
    <status>OK</status> 
    <result> 
    <type>postal_code</type> 
    <formatted_address>San Francisco, CA 94102, USA</formatted_address> 
    <address_component> 
     <long_name>94102</long_name> 
     <short_name>94102</short_name> 
     <type>postal_code</type> 
    </address_component> 
    <address_component> 
     <long_name>San Francisco</long_name> 
     <short_name>SF</short_name> 
     <type>locality</type> 
     <type>political</type> 
    </address_component> 
    <address_component> 
     <long_name>San Francisco County</long_name> 
     <short_name>San Francisco County</short_name> 
     <type>administrative_area_level_2</type> 
     <type>political</type> 
    </address_component> 
    <address_component> 
     <long_name>California</long_name> 
     <short_name>CA</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>37.7786871</lat> 
     <lng>-122.4212424</lng> 
     </location> 
     <location_type>APPROXIMATE</location_type> 
     <viewport> 
     <southwest> 
      <lat>37.7694409</lat> 
      <lng>-122.4298490</lng> 
     </southwest> 
     <northeast> 
      <lat>37.7892260</lat> 
      <lng>-122.4034491</lng> 
     </northeast> 
     </viewport> 
     <bounds> 
     <southwest> 
      <lat>37.7694409</lat> 
      <lng>-122.4298490</lng> 
     </southwest> 
     <northeast> 
      <lat>37.7892260</lat> 
      <lng>-122.4034491</lng> 
     </northeast> 
     </bounds> 
    </geometry> 
    <place_id>ChIJs88qnZmAhYARk8u-7t1Sc2g</place_id> 
    </result> 
</GeocodeResponse> 
+0

我不國家和地區不要在你的XML中看到州/市,你的意思是地址? –

+0

狀態將爲'administrative_area_level_1',城市爲'locality' – user1186050

+0

,所以我正在尋找'舊金山'和'加州' – user1186050

回答

1

你可以做到這一點,以獲得從Xml

var statesOrCity = doc.Descendants("address_component") 
     .Where(e=>e.Elements("type").Any(x=>x.Value == "administrative_area_level_1" || x.Value == "locality")) 
     .Select(c=> new { 
      longname =c.Element("long_name").Value, 
      shortname =c.Element("short_name").Value, 
      State = c.Element("type").Value== "locality"? "State" : "City" 
     }); 

工作Demo