代码
try{
URL url = new URL("http://maps.googleapis.com/maps/api/geocode/xml?address=Riyadh&sensor=false");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while(null != (line = reader.readLine())){
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
输出:
Server is Ready....
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>OK</status>
<result>
<type>locality</type>
<type>political</type>
<formatted_address>Riyadh Saudi Arabia</formatted_address>
<address_component>
<long_name>Riyadh</long_name>
<short_name>Riyadh</short_name>
<type>locality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Riyadh Province</long_name>
<short_name>Riyadh Province</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Saudi Arabia</long_name>
<short_name>SA</short_name>
<type>country</type>
<type>political</type>
</address_component>
<geometry>
<location>
<lat>24.7135517</lat>
<lng>46.6752957</lng>
</location>
<location_type>APPROXIMATE</location_type>
<viewport>
<southwest>
<lat>24.2939113</lat>
<lng>46.2981033</lng>
</southwest>
<northeast>
<lat>25.1564724</lat>
<lng>47.3469543</lng>
</northeast>
</viewport>
<bounds>
<southwest>
<lat>24.2939113</lat>
<lng>46.2981033</lng>
</southwest>
<northeast>
<lat>25.1564724</lat>
<lng>47.3469543</lng>
</northeast>
</bounds>
</geometry>
<place_id>ChIJmZNIDYkDLz4R1Z_nmBxNl7o</place_id>
</result>
</GeocodeResponse>
我正在尝试使用Google地理编码API来获取城市的坐标,但我遇到的问题是如何解析XML响应以检索包含在({{{{{{ 1}})部分。