SAX处理XML实例
时间:2011-04-19 来源:livedba
本实例利用SAX(全称是Simple API For XML)处理Google API返回的天气预报数据,数据格式是XML,API地址是http://www.google.com/ig/api?hl=zh-cn&weather=BeiJing
下面是核心代码:
首先是天气预报实体:
public class WeatherBean implements Serializable{
private static final long serialVersionUID = 1L;
//今天天气
private String day;
private String lowTemp;
private String highTemp;
private String imageUrl;
private String condition;
因为SAX是基于事件的,必须定义一个Handler继承DefaultHandler
public class WeatherReport extends DefaultHandler{
private boolean inForcast;
private WeatherBean currentWeather;
private List<WeatherBean> weatherList;
public WeatherReport(){
weatherList = new ArrayList<WeatherBean>();
this.inForcast=false;
}
public boolean isInForcast() {
return inForcast;
}
public void setInForcast(boolean inForcast) {
this.inForcast = inForcast;
}
public List<WeatherBean> getWeatherList() {
return weatherList;
}
public void setWeatherList(List<WeatherBean> weatherList) {
this.weatherList = weatherList;
}
@Override
public void startDocument(){
}
@Override
public void startElement(String uri,String localName,String qName,Attributes atts) throws SAXException{
Log.v("weather","开始解析XML");
String tagName = localName.length()!=0?localName:qName;
tagName = tagName.toLowerCase();
if(tagName.equals("forecast_conditions")){
inForcast = true;
currentWeather = new WeatherBean();
}
if(inForcast){
if(tagName.equals("day_of_week")){
currentWeather.setDay(atts.getValue("data"));
}else if(tagName.equals("low")){
currentWeather.setLowTemp(atts.getValue("data"));
}else if(tagName.equals("high")){
currentWeather.setHighTemp(atts.getValue("data"));
}else if(tagName.equals("icon")){
currentWeather.setImageUrl(atts.getValue("data"));
}else if(tagName.equals("condition")){
currentWeather.setCondition(atts.getValue("data"));
}
}
}
@Override
public void endElement(String uri,String localName,String qName) throws SAXException{
Log.v("weather","结束解析XML");
String tagName = localName.length()!=0?localName:qName;
tagName = tagName.toLowerCase();
if(tagName.equals("forecast_conditions")) {
inForcast = false;
weatherList.add(currentWeather);
}
}
}
然后是Activity的核心代码:
try{
WeatherReport wr = new WeatherReport();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xml = parser.getXMLReader();
URL url = new URL("