android利用SAX解析xml(以解析谷歌天气预报xml预报为例)
package com.mars.android;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class CurrentWeather extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button submit=(Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*从google上获得图标*/
try{
String city=((EditText)findViewById(R.id.cityname))
.getText().toString().trim();
String querystr="http://www.google.com/ig/api?weather="+city;
URL aURL=new URL(querystr.replace(" ", "%20"));
/*从SAXParserFactory中获取SAXParser*/
Log.v("querystr",querystr);
Log.v("querystr", querystr.replace(" ", "%20"));
/*创建一个SAXParserFactory对象*/
SAXParserFactory spf=SAXParserFactory.newInstance();
/*利用SAXParserFactory对象spf的newSAXParser()方法生成一个SAXParser对象*/
SAXParser sp=spf.newSAXParser();
XMLReader xr=sp.getXMLReader();//从SAXParser中得到XMLReader
/*创建一个解析xml文件的GoogleWeatherHandler对象gwh*/
GoogleWeatherHandler gwh=new GoogleWeatherHandler();
/*设定XMLReader类的xml处理对象*/
xr.setContentHandler(gwh);
/*解析XML文件内容*/
xr.parse(new InputSource(aURL.openStream()));
/*下面进行图片的请求 并生成一幅bmp图像*/
URL iconurl=new URL("http://www.google.com"+gwh.getIconURL());
URLConnection conn= iconurl.openConnection();
conn.connect();
//获得图像的字符流
InputStream is=conn.getInputStream();
BufferedInputStream bis=new BufferedInputStream(is,8192);
ImageView iv=(ImageView)findViewById(R.id.iconofwheather);
Bitmap bm=null;//生成了一张bmp图像
bm=BitmapFactory.decodeStream(bis);
bis.close();
is.close();//关闭流
System.out.println(bm.getHeight());
iv.setImageBitmap(bm);
TextView tv1=(TextView)findViewById(R.id.condition);
tv1.append(gwh.getCurrent_condition());
TextView tv2=(TextView)findViewById(R.id.temperature);
tv2.append(gwh.getCurrent_temp().toString()+"摄氏度");
TextView tv3=(TextView)findViewById(R.id.humidity);
tv3.append(gwh.getCurrent_hum().replace("Humidity", ""));
System.out.println(tv1.getText().toString());
System.out.println(tv2.getText().toString());
System.out.println(tv3.getText().toString());
}
catch(Exception e){
Log.e("error", e.toString());
}
}
});
}
}
上面是一个activity用于显示解析xml得出的内容。下面是一个继承自DefaultHandler的类 专门用于处理XML
package com.mars.android;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class GoogleWeatherHandler extends DefaultHandler{
private boolean in_forecast_information = false;
private boolean in_current_conditions = false;
private boolean in_forecast_conditions = false;
private Integer current_temp;
private String current_condition;
private String current_hum;
private String iconURL;
// private String forecast_date;
private boolean usingSITemperature = false; // false为华氏度,true为摄氏度
public Integer getCurrent_temp() {
return current_temp;
}
public void setCurrent_temp(Integer currentTemp) {
current_temp = currentTemp;
}
public String getCurrent_condition() {
return current_condition;
}
public void setCurrent_condition(String currentCondition) {
current_condition = currentCondition;
}
public String getCurrent_hum() {
return current_hum;
}
public void setCurrent_hum(String currentHum) {
current_hum = currentHum;
}
public String getIconURL() {
return iconURL;
}
public void setIconURL(String iconURL) {
this.iconURL = iconURL;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equals("forecast_information")) {
this.in_forecast_information = false;
} else if (localName.equals("current_conditions")) {
this.in_current_conditions = false;
} else if (localName.equals("forecast_conditions")) {
this.in_forecast_conditions = false;
}
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
// super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equals("forecast_information")) {
this.in_forecast_information = true;
} else if (localName.equals("current_conditions")) {
this.in_current_conditions = true;
} else if (localName.equals("forecast_conditions")) {
this.in_forecast_conditions = true;
} else {
String dataAttribute = attributes.getValue("data");
// 'Inner' Tags of "<forecast_information>"
if (localName.equals("city")) {
} else if (localName.equals("postal_code")) {
} else if (localName.equals("latitude_e6")) {
/* One could use this to convert city-name to Lat/Long. */
} else if (localName.equals("longitude_e6")) {
/* One could use this to convert city-name to Lat/Long. */
} else if (localName.equals("forecast_date")) {
} else if (localName.equals("current_date_time")) {
} else if (localName.equals("unit_system")) {
if (dataAttribute.equals("SI"))
this.usingSITemperature = true;
}
// SHARED(!) 'Inner' Tags within "<current_conditions>" AND
// "<forecast_conditions>"
else if (localName.equals("day_of_week")) {
if (this.in_current_conditions) {
//可扩展
} else if (this.in_forecast_conditions) {
//可扩展
}
} else if (localName.equals("icon")) {
if (this.in_current_conditions) {
this.setIconURL(dataAttribute);
} else if (this.in_forecast_conditions) {
//可扩展
}
} else if (localName.equals("condition")) {
if (this.in_current_conditions) {
this.setCurrent_condition(dataAttribute);
} else if (this.in_forecast_conditions) {
//可扩展
}
}
// 'Inner' Tags within "<current_conditions>"
else if (localName.equals("temp_f")) {
//this.setCurrentTemp(Integer.parseInt(dataAttribute));
} else if (localName.equals("temp_c")) {
this.setCurrent_temp(Integer.parseInt(dataAttribute));
} else if (localName.equals("humidity")) {
this.setCurrent_hum(dataAttribute);
} else if (localName.equals("wind_condition")) {
//可扩展
}
// 'Inner' Tags within "<forecast_conditions>"
else if (localName.equals("low")) {
int temp = Integer.parseInt(dataAttribute);
if (this.usingSITemperature) {
//可扩展
} else {
//可扩展
}
} else if (localName.equals("high")) {
//int temp = Integer.parseInt(dataAttribute);
if (this.usingSITemperature) {
//可扩展
} else {
//可扩展
}
}
}
}
}