欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sax 解析 xml

程序员文章站 2022-05-28 08:44:06
...
HandlerXML.java--处理xml

package cn.com.songjy.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class HandlerXML extends DefaultHandler {

List<ForecastCondition> forecast_conditions = new ArrayList<ForecastCondition>();
ForecastCondition forecast_condition = new ForecastCondition();
Map<String, Object> forecast_information = new HashMap<String, Object>();
Map<String, Object> current_condition = new HashMap<String, Object>();
boolean current_condition_flag = false;
boolean forecast_information_flag = false;
boolean forecast_conditions_flag = false;

public List<ForecastCondition> getForecastConditions() {
return forecast_conditions;
}


public Map<String, Object> getForecastInformation(){
return forecast_information;
}

public Map<String, Object> getCurrentConditions(){
return current_condition;
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {

if("forecast_information".equals(qName))
forecast_information_flag = true;

if(forecast_information_flag && "city".equals(qName))
forecast_information.put("city", attributes.getValue("data"));
if(forecast_information_flag && "forecast_date".equals(qName))
forecast_information.put("forecast_date", attributes.getValue("data"));
if(forecast_information_flag && "current_date_time".equals(qName))
forecast_information.put("current_date_time", attributes.getValue("data"));

if("current_conditions".equals(qName))
current_condition_flag = true;

if(current_condition_flag && "condition".equals(qName))
current_condition.put("condition", attributes.getValue("data"));
if(current_condition_flag && "temp_f".equals(qName))
current_condition.put("temp_f", attributes.getValue("data"));
if(current_condition_flag && "temp_c".equals(qName))
current_condition.put("temp_c", attributes.getValue("data"));
if(current_condition_flag && "humidity".equals(qName))
current_condition.put("humidity", attributes.getValue("data"));
if(current_condition_flag && "icon".equals(qName))
current_condition.put("icon", attributes.getValue("data"));
if(current_condition_flag && "wind_condition".equals(qName))
current_condition.put("wind_condition", attributes.getValue("data"));

if("forecast_conditions".equals(qName))
forecast_conditions_flag = true;

if (forecast_conditions_flag && "day_of_week".equals(qName)) {
String week = attributes.getValue("data");
forecast_condition = new ForecastCondition();//不可省略,否则将永远是最后一条记录
forecast_condition.setWeek(week);
}

if (forecast_conditions_flag && "low".equals(qName)) {
int low = Integer.parseInt(attributes.getValue("data"));
forecast_condition.setLow(low);

}
if (forecast_conditions_flag && "high".equals(qName)) {
int hight = Integer.parseInt(attributes.getValue("data"));
forecast_condition.setHight(hight);

}

if (forecast_conditions_flag && "icon".equals(qName)) {
String icon = attributes.getValue("data");
forecast_condition.setIcon(icon);

}

if (forecast_conditions_flag && "condition".equals(qName)) {
String condition = attributes.getValue("data");
forecast_condition.setCondition(condition);

}

}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {

if("current_conditions".equals(qName))
current_condition_flag = false;
if("forecast_information".equals(qName))
forecast_information_flag = false;
if("forecast_conditions".equals(qName))
forecast_conditions_flag = false;

if ("forecast_conditions".equals(qName)) {
forecast_conditions.add(forecast_condition);
}
}

}



ParsersXML.java--显示处理结果

package cn.com.songjy.xml;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ParsersXML {

public static void main(String[] args) {
Map<String, Object> map = readXml();
List<ForecastCondition> forecastConditions = (List<ForecastCondition>) map.get("forecastConditions");
Map<String, Object> forecast_information = (Map<String, Object>) map.get("forecast_information");
Map<String, Object> current_condition = (Map<String, Object>) map.get("current_condition");

System.out.println("**********预测数据**********");
for (ForecastCondition weather : forecastConditions) {
System.out.println(weather.toString());
}

System.out.println("**********预报信息**********");

for (String key : forecast_information.keySet()) {
System.out.println(forecast_information.get(key).toString());
}

System.out.println("**********当天数据**********");
for (String key : current_condition.keySet()) {
System.out.println(current_condition.get(key).toString());
}

}

public static Map<String, Object> readXml() {
Map<String, Object> map = new HashMap<String, Object>();
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
InputSource inputSource = new InputSource(new StringReader(getWeatherAsString()));
HandlerXML handlerXML = new HandlerXML();
try {
parser.parse(inputSource, handlerXML);
map.put("forecastConditions", handlerXML.getForecastConditions());
map.put("forecast_information", handlerXML.getForecastInformation());
map.put("current_condition", handlerXML.getCurrentConditions());
return map;
} catch (IOException e) {
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}

//调用公开API获取XML数据
public static String getWeatherAsString() {
String strUrl = "http://www.google.com/ig/api?hl=zh-cn&weather=Ganzhou,Jiangxi";
HttpGet getRequest = new HttpGet(strUrl);
DefaultHttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(getRequest);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}



执行效果如下:

**********预测数据**********
预测数据 [week=周四, hight=33, low=24, icon=/ig/images/weather/thunderstorm.gif, condition=雷阵雨]
预测数据 [week=周五, hight=32, low=24, icon=/ig/images/weather/chance_of_storm.gif, condition=可能有暴风雨]
预测数据 [week=周六, hight=31, low=24, icon=/ig/images/weather/chance_of_storm.gif, condition=可能有暴风雨]
预测数据 [week=周日, hight=31, low=24, icon=/ig/images/weather/chance_of_storm.gif, condition=可能有暴风雨]
**********预报信息**********
2012-06-07 17:00:00 +0000
2012-06-07
Ganzhou, Jiangxi
**********当天数据**********
/ig/images/weather/mostly_cloudy.gif
湿度: 60%
88
风向: 西南、风速:3 米/秒
多云
31


ForecastCondition.java--对象

package cn.com.songjy.xml;

public class ForecastCondition {

private String week;
private int low;
private int hight;
private String icon;
private String condition;

@Override
public String toString() {
return "预测数据 [week=" + week + ", hight=" + hight
+ ", low=" + low + ", icon=" + icon + ", condition=" + condition + "]";
}

public String getWeek() {
return week;
}

public void setWeek(String week) {
this.week = week;
}

public int getLow() {
return low;
}

public void setLow(int low) {
this.low = low;
}

public int getHight() {
return hight;
}

public void setHight(int hight) {
this.hight = hight;
}

public String getIcon() {
return icon;
}

public void setIcon(String icon) {
this.icon = icon;
}

public String getCondition() {
return condition;
}

public void setCondition(String condition) {
this.condition = condition;
}

}



所需jar包可从附件下载

引自:[url]http://www.2cto.com/kf/201204/127466.html[/url]
相关标签: sax xml解析