我正在使用在线服务,更好地说,学习如何使用它们。我必须从Yahoo的天气API请求天气数据,并在JSon中阅读。但似乎雅虎现在不提供Json中的数据,所以我必须用XML来获取它。
我已经完成了在JSon中获取它的代码,但我不确定如何使用XML。
这是请求代码:
URL url = null;
HttpURLConnection connection = null;
url = new URL(WEATHER_URL + code);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
//Parse response here
WeatherInfo info = readWeatherInfo(is);
return info;
这就是我在JSon中获得它的方式:
private WeatherInfo readWeatherInfo(InputStream is){
if (is == null)
return null;
WeatherInfo info = new WeatherInfo();
JsonReader reader = null;
try {
reader = new JsonReader(new InputStreamReader(is));
reader.beginObject();
while (reader.hasNext()){
if (isCancelled()) break;
String name = reader.nextName();
if (name.equals(LOCATION_NAME)){ //Location
reader.beginObject();
while (reader.hasNext()){
String name2 = reader.nextName();
if (name2.equals(CITY_NAME)){
info.city = reader.nextString();
} else reader.skipValue();
}
reader.endObject();
} else if (){
//...
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return info;
}
}
}
这就是我开始用XML做的但不确定的方式:
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(is));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT){
switch (eventType) {
case XmlPullParser.START_TAG:
while (parser.next()) {
String name = parser.getName();
if (name.equals(LOCATION_NAME)){
String name2 = parser.getName();
if (name2.equals(CITY_NAME)) {
info.city = parser.getText();
}
}
else if (name.equals(CONDITION_NAME)){
//...
}
更新 - XML文件链接: