本文为已归档的历史博客内容,其内容可能随着时间发生已经改变。
This article is archived from my previous blog, so the content maybe have changed now.


Java 代码——在 URL 使用 SAX 解析 XML

前言: 此代码只是为了完成作业,后来经本人修改可以运行在 Android 手机上,不过略有 Bug,暂不放出 Android 版本代码。 请勿抄袭。

Info: IDE: Eclipse System: Mac OS X 11.1

难点: 此 API 需要用 GZIP 解压后方可解析,否则为乱码,且非编码方式原因。

Main.java

import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

public class Main {
	private final static String WEATHER_XML_API = "http://wthrcdn.etouch.cn/WeatherApi?citykey=";
	private final static String cityID = "101180701"; 
	public static void main(String[] args) {
		URL url = null;
		try {
			url = new URL(WEATHER_XML_API + cityID);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		URLConnection urlc = null;
		GZIPInputStream in = null;
		try {
			urlc = url.openConnection();
			urlc.setDoInput(true);
			InputStream is = urlc.getInputStream();
			in = new GZIPInputStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		WeatherHandler wh = new WeatherHandler();
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();  
		    SAXParser parser = factory.newSAXParser();
		    parser.parse(in, wh);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ArrayList<Weather> WeatherInfo = wh.getWeatherInfo();
		for (Weather w: WeatherInfo) {
			System.out.println(w.toString());
		}
	}
}

WeatherHandler.java

import java.util.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class WeatherHandler extends DefaultHandler {
	private static final String CITY = "city";
	private static final String UPDATE_TIME = "updatetime";
	private static final String TEMPERATURE = "wendu";
	private static final String WIND_POWER = "fengli";
	private static final String WIND_DIRECTION = "fengxiang";
	
	private ArrayList<Weather> WeatherInfo = new ArrayList<Weather>();;
	private Weather currentCity = null;
	private String tagName = null;

	public ArrayList<Weather> getWeatherInfo() {
		return WeatherInfo;
	}

//	@Override
//	public void startDocument() throws SAXException {
//		super.startDocument();
//	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		if (qName.equals(CITY)){
			currentCity = new Weather();
			if (attributes != null) {
				currentCity.setCity(attributes.getValue(CITY));
				currentCity.setUpdateTime(attributes.getValue(UPDATE_TIME));
				currentCity.setTemperature(attributes.getValue(TEMPERATURE));
				currentCity.setWindPower(attributes.getValue(WIND_POWER));
				currentCity.setWindDirection(attributes.getValue(WIND_DIRECTION));
				
			}
		}
		tagName = qName;
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		if (tagName != null) {
			String data = new String(ch, start, length);
			if (tagName.equals(CITY)) {
				currentCity.setCity(data);
			} else if (tagName.equals(UPDATE_TIME)) {
				currentCity.setUpdateTime(data);
			} else if (tagName.equals(TEMPERATURE)) {
				currentCity.setTemperature(data);
			} else if (tagName.equals(WIND_POWER)) {
				currentCity.setWindPower(data);
			} else if (tagName.equals(WIND_DIRECTION)) {
				currentCity.setWindDirection(data);
			}
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
		if (qName.equals(CITY)){
			WeatherInfo.add(currentCity);
		}
		tagName = null;
	} 
	
//	@Override 
//    public void endDocument() throws SAXException {
//        super.endDocument(); 
//    } 
}

Weather.java

public class Weather {
	private String city;
	private String updateTime;
	private String temperature;
	private String windPower;
	private String windDirection;
	
	public void setCity(String city) {
		this.city = city;
	}
	
	public String getCity() {
		return city;
	}
	
	public void setUpdateTime(String updateTime) {
		this.updateTime = updateTime;
	}
	
	public String getUpdateTime() {
		return updateTime;
	}
	
	public void setTemperature(String temperature) {
		this.temperature = temperature;
	}
	
	public String getTemperature() {
		return temperature;
	}
	
	public void setWindPower(String windPower) {
		this.windPower = windPower;
	}
	
	public String getWindPower() {
		return windPower;
	}
	
	public void setWindDirection(String windDirection) {
		this.windDirection = windDirection;
	}
	
	public String getWindDirection() {
		return windDirection;
	}
	
	@Override
	public String toString() {
		String s = "\n";
		String s1 = "City: ";
		String s2 = "Update Time: ";
		String s3 = "Temperature: ";
		String s4 = "Wind Power: ";
		String s5 = "Wind Direction: ";

		return s1 + city + s
				+ s2 + updateTime + s
				+ s3 + temperature + s
				+ s4 + windPower + s
				+ s5 + windDirection;
	}
}