解析xml的另外一种方法(Google weather)
今天学习了一下如何获取天气,也学习了另外一种解析xml的方法
通过google api获取的天气的xml
<?xml version="1.0"?><xml_api_reply version="1"><weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1"row="0" section="0"><forecast_information><city data="Beijing, Beijing" /><postal_code data="beijing" /><latitude_e6 data="" /><longitude_e6 data="" /><forecast_date data="2011-01-13" /><current_date_time data="2011-01-13 16:00:00 +0000" /><unit_system data="US" /></forecast_information><current_conditions><condition data="Clear" /><temp_f data="23" /><temp_c data="-5" /><humidity data="Humidity: 39%" /><icon data="/ig/images/weather/sunny.gif" /><wind_condition data="Wind: N at 2 mph" /></current_conditions><forecast_conditions><day_of_week data="Thu" /><low data="12" /><high data="37" /><icon data="/ig/images/weather/sunny.gif" /><condition data="Clear" /></forecast_conditions><forecast_conditions><day_of_week data="Fri" /><low data="8" /><high data="28" /><icon data="/ig/images/weather/sunny.gif" /><condition data="Clear" /></forecast_conditions><forecast_conditions><day_of_week data="Sat" /><low data="12" /><high data="26" /><icon data="/ig/images/weather/sunny.gif" /><condition data="Clear" /></forecast_conditions><forecast_conditions><day_of_week data="Sun" /><low data="12" /><high data="30" /><icon data="/ig/images/weather/sunny.gif" /><condition data="Clear" /></forecast_conditions></weather></xml_api_reply>
class getWeather implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stubString weather = "";String url = "http://www.google.com/ig/api?&weather=beijing";DefaultHttpClient client = new DefaultHttpClient();HttpUriRequest req = new HttpGet(url);HttpResponse resp;try {resp = client.execute(req);HttpEntity ent = resp.getEntity();InputStream stream = ent.getContent();//printEntity(stream);DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();Document d = b.parse(new InputSource(stream));NodeList n = d.getElementsByTagName("forecast_conditions");for (int i = 0; i < n.getLength(); i++) {weather += n.item(i).getChildNodes().item(0).getAttributes().item(0).getNodeValue();weather += ", ";weather += (Integer.parseInt(n.item(i).getChildNodes().item(1).getAttributes().item(0).getNodeValue()) - 32) * 5 / 9;weather += " ~ ";weather += (Integer.parseInt(n.item(i).getChildNodes().item(2).getAttributes().item(0).getNodeValue()) - 32) * 5 / 9;weather += ", ";weather += n.item(i).getChildNodes().item(4).getAttributes().item(0).getNodeValue();weather += "\n";}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ParserConfigurationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SAXException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(" weather is " + weather);}};