我正在使用在線服務,更好地說,學習如何使用它們。我必須從雅虎的天氣API請求天氣數據,並在JSon中讀取它。但似乎雅虎現在不提供Json中的數據,所以我必須使用XML。以XML獲取在線天氣API數據
我已經完成了在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文件鏈接:
http://weather.yahooapis.com/forecastrss?w=766273&u=c
XML的示例會很有幫助。 – s1m3n
@ s1m3n你是什麼意思?我沒有更多的代碼,這是我所擁有的。正如我所說,我已經做到了用JSon來實現它,但不知道如何使用XML。 – masmic
您正在解析XML,但您沒有提供XML結構的示例,所以我不知道您的XML解析代碼是否正常。我想我可以查看雅虎API,但這是你的問題。 – s1m3n