java sax解析xml例子_sax解析xml案例一

packagecom.ljq.sax;importjava.util.ArrayList;importjava.util.List;importorg.xml.sax.Attributes;importorg.xml.sax.SAXException;importorg.xml.sax.helpers.DefaultHandler;importcom.ljq.entity.Forecast;importcom.ljq.entity.Weather;publicclassWeatherSaxextendsDefaultHandler {privateWeather weather;privateForecast forecast;privateListforecasts;privateString preTag;

@OverridepublicvoidstartDocument()throwsSAXException {

weather=newWeather();

forecasts=newArrayList();

}

@Overridepublicvoidcharacters(char[] ch,intstart,intlength)throwsSAXException {

}

@OverridepublicvoidstartElement(String uri, String localName, String name,

Attributes attr)throwsSAXException {if("city".equals(name)) {

weather.setCity(attr.getValue("data"));//等价于weather.setCity(attr.getValue("data"));}if("forecast_date".equals(name)) {

weather.setForecase_date(attr.getValue("data"));

}if("current_date_time".equals(name)) {

weather.setCurrent_date_time(attr.getValue("data"));

}if("current_conditions".equals(name)){

preTag=name;

}if("condition".equals(name)&&"current_conditions".equals(preTag)) {

weather.setCurrent_condition(attr.getValue("data"));

}if("humidity".equals(name)) {

weather.setCurrent_humidity(attr.getValue("data"));

}if("icon".equals(name)&&"current_conditions".equals(preTag)) {

weather.setCurrent_image_url(attr.getValue("data"));

}if("wind_condition".equals(name)) {

weather.setCurrent_wind(attr.getValue("data"));

}if("forecast_conditions".equals(name)) {

preTag=name;//记录标识,用来区分相同节点的不同父节点forecast=newForecast();

}if("day_of_week".equals(name)) {

forecast.setDay_of_week(attr.getValue("data"));

}if("low".equals(name)) {

forecast.setLow(attr.getValue("data"));

}if("high".equals(name)) {

forecast.setHigh(attr.getValue("data"));

}if("icon".equals(name)&&"forecast_conditions".equals(preTag)) {

forecast.setImage_url(attr.getValue("data"));

}if("condition".equals(name)&&"forecast_conditions".equals(preTag)) {

forecast.setCondition(attr.getValue("data"));

}

}

@OverridepublicvoidendElement(String uri, String localName, String name)throwsSAXException {if("forecast_conditions".equals(name)) {

forecasts.add(forecast);

forecast=null;

}if("weather".equals(name)) {

weather.setForecasts(forecasts);

}

}publicWeather getWeather() {returnweather;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值