官方提供api地址:
http://developer.yahoo.com/yql/guide/running-chapt.html
http://developer.yahoo.com/weather/#terms
本例提供解析代码。api数据格式以上地址可查看。
public void paserxml() throws UnsupportedEncodingException {
String cityCode = getCityCode("shenzhen");
String str = "http://weather.yahooapis.com/forecastrss?w="+cityCode+"&u=c";
try {
domfac = DocumentBuilderFactory
.newInstance();
dombuilder = domfac.newDocumentBuilder();
// NodeList channels;
URL ur = new URL(str);
HttpURLConnection urlConnection = (HttpURLConnection) ur.openConnection();//打开一个连接
int code1 =urlConnection.getResponseCode();
Log.e("liyongjun", "code = "+code1);
doc = dombuilder.parse(urlConnection.getInputStream());
root = doc.getDocumentElement(); //rss
//channels = root.getChildNodes(); //channels
NodeList list = doc.getElementsByTagName("yweather:forecast");
int size = list.getLength();
for(int i = 0; i<(list.getLength());i++) {
//遍历每一个元素
Element elt = (Element) list.item(i);
String date = elt.getAttribute("date");
String day = elt.getAttribute("day");
String text = elt.getAttribute("text");
String low = elt.getAttribute("low");
String high = elt.getAttribute("high");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("liyongjun", "网络连接超时!");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
获得城市代码(yahoo提供)
public String getCityCode(String name) throws UnsupportedEncodingException{
String code = null;
String paramString="http://query.yahooapis.com/v1/public/yql?q=select*from%20geo.places%20where%20text=%27"+name+"%27";
try {
domfac = DocumentBuilderFactory
.newInstance();
dombuilder = domfac.newDocumentBuilder();
NodeList results;
URL url = new URL(paramString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();//打开一个连接
doc = dombuilder.parse(urlConnection.getInputStream());
root = doc.getDocumentElement();
results = root.getChildNodes(); //results
if(results.getLength() > 0){
Node node = results.item(0).getFirstChild(); //得到 item 第一个 place
NodeList places = node.getChildNodes(); //得到place下所有子节点
code = places.item(0).getFirstChild().getNodeValue(); //指向第一个place,拿到第一个子节点 wodid 获得value
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return code;
}
查询城市ID API
http://query.yahooapis.com/v1/public/yql?q=select*from geo.places where text= ' "+name+" ' ";
name:即需要的查询城市的英文名。