I'm working with online services, better said, learning how to work with them. I have to request weather data from Yahoo's weather API, and read it in JSon. But it seems that Yahoo doesn't provide now the data in Json, so I have to get it in XML.
I have the code done to get it in JSon, but I'm not sure on how to do it with XML.
This is the request code:
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;
This is how I get it in 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;
}
}
}
And this is the way I've started to do it in XML but not sure about it:
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)){
//...
}
UPDATE - XML file link: