天天看点

Android XML的操作(SAX)“.NET研究”

  在android平台下操作xml方式有很多种,常见的为SAX(Simple APIfor XML)和DOM(Document Object Model)。

  SAX操作xml的特点是当读取xml文件的时候会随时触发事件,通过事件来处理当前读取到的内容。这一点是跟dom有所不同的,dom是全部读取完后在进行操作。

  现在这个实例是以SAX进行XML操作的!

  这个例子是读取Google的天气预报为例子做成了,使用的XML地址如下:http://www.google.com/ig/api?weather=beijing&hl=zh-cn

  通过互联网获取天气的XML代码,然后再通过SAX进行读取:

  在例子中只是读取了当前的时时天气,没有对预报的内容进行读取,等以后再完善吧:

  首先根据XML文件抽象出一个类来,我获取到的XML代码如下:

<?xml version="1.0" ?>

<xml_api_reply version="1">

<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1"

row="0" section="0">

<forecast_information>

<city data="Beijing, Beijing" />

<postal_code data="beijing" />

<latitude_e6 data="" />

<longitude_e6 data="" />

<forecast_date data="2010-12-27" />

<current_date_time data="2010-12-28 04:00:00 +0000" />

<unit_system data="SI" />

</forecast_information>

<current_conditions>

<temp_f data="28" />

<temp_c data="-2" />

<humidity data="湿度: 27%" />

<icon data="/ig/images/weather/sunny.gif" />

<wind_condition data="风向: 西北、风速:7 米/秒" />

</current_conditions>

<forecast_conditions>

<low data="-12" />

<high data="6" />

</forecast_conditions>

<day_of_week data="周二" />

<low data="-11" />

<high data="1" />

<condition data="晴" />

<day_of_week data="周三" />

<high data="2" />

<icon data="/ig/images/weather/chance_of_snow.gif" />

<condition data="可能降雪" />

<day_of_week data="周四" />

<low data="-13" />

<high data="-2" />

</weather>

</xml_api_reply>

  不同时间可能获取到的不同,但是格式应该是一致的!下面是根据这个抽象出来的类:

package com.SAXXMLReader;

public class NowWeather {

private String condition;

private String temp_f;

private String temp_c;

private String humidity;

private String icon;

private String wind_condition;

public NowWeather() {

}

public void setcondition(String condition) {

this.condition = condition;

public void settempf(String temp_f) {

this.temp_f = temp_f;

public void settempc(String temp_c) {

this.temp_c = temp_c;

public void sethumidity(String humidity) {

this.humidity = humidity;

public void seticon(String icon) {

this.icon = icon;

public void setwindcondition(String wind_condition) {

this.wind_condition = wind_condition;

public String getNowWeather()

{

StringBuilder strBuilder = new StringBuilder();

strBuilder.append(condition+"\n");

strBuilder.append(temp_f+"\n");

strBuilder.append(temp_c+"\n");

strBuilder.append(humidity+"\n");

strBuilder.append(icon+"\n");

strBuilder.append(wind_condition+"\n");

return strBuilder.toString();

  这个类保存的是获取到的数据,形式可能有多种,这个根据个人的习惯进行书写吧。写到这里,因为在SAX中使用的时候需要有一个DefaultHandler类的继承,实现如下:

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class WeatherHandler extends DefaultHandler {

private final String CURRENT_CONDITIONS = "current_conditions"; // 当前

private final String forecast_conditions = "forecast_conditions"; // 当前

// 实时天气信息

private boolean is_Current_Conditions = false;

// 预报天气信息

private boolean is_Forecast_Conditions = false;

NowWeather nowWeather = new NowWeather();

@Override

public void characters(char[] ch, int start, int length)

throws SAXException {

// TODO Auto-generated method stub

super.characters(ch, start, length);

public void startDocument() throws SAXException {

super.startDocument();

public WeatherHandler() {

public void startElement(String uri, String localName, String qName,

Attributes attributes) throws SAXException {

// super.startElement(uri, localName, qName, attributes);

String dataAttribute = "OK";

// Log.d("WeatherHandler", localName);

if (localName.equals(CURRENT_CONDITIONS)) {

Log.d("WeatherHandler", localName);

is_Current_Conditions = true;

} else if (localName.equals(forecast_conditions)) {

is_Current_Conditions = false;

} else {

dataAttribute = attributes.getValue("data");

if (this.is_Current_Conditions) {

Log.d("WeatherHandler_1", dataAttribute);

// this.nowWeather.setcondition(dataAttribute);

if (localName.equals("condition")) {

this.nowWeather.setcondition(dataAttribute);

} else if (localName.equals("temp_f")) {

this.nowWeather.settempf(dataAttribute);

} else if (localName.equals("temp_c")) {

this.nowWeather.settempc(dataAttribute);

} else if (localName.equals("humidity")) {

this.nowWeather.sethumidity(dataAttribute);

} else if (localName.equals("icon")) {

this.nowWeather.seticon(dataAttribute);

} else if (localName.equals("wind_condition")) {

this.nowWeather.setwindcondition(dataAttribute);

} else if (this.is_Forecast_Conditions) {

上海企业网站制作/> // Log.d("WeatherHandler_1", dataAttribute);

public String getNowWeather() {

return nowWeather.getNowWeather();

public void endDocument() throws SAXException {

super.endDocument();

public void endElement(String uri, String localName, String name)

  在这里实现了读取XML代码,并且保存到抽象出来的类中,以供调用。下面的方法是对这个类的调用,通过调用,获取内容:

SAXParserFactory faction =SAXParserFactory.newInstance();

SAXParser parser = faction.newSAXParser();

WeatherHandler handler = new WeatherHandler();

XMLReader reader = parser.getXMLReader();

reader.setContentHandler(handler);

URL url = new URL(SRC);

HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();

//httpconn.getInputStream();

InputStream inStream =httpconn.getInputStream();// this.getResources().openRawResource(R.xml.weather);

InputStreamReader isReader = new InputStreamReader(inStream,"GBK");

//BufferedReader buffRreader = new BufferedReader(isReader);

//String line="";

//String data = "";

//

//while((line=buffRreader.readLine())!=null)

// data += line;

//text1.setText(data);

//Toast.makeText(this,data, Toast.LENGTH_LONG).show();

InputSource inputSource = new InputSource(isReader);

reader.parse(inputSource);

text1.setText(handler.getNowWeather());

//Toast.makeText(this, handler.getNowWeather(), Toast.LENGTH_LONG).show();

  这里直接通过获取网上的XML进行的解析,当然你也可以读取本地的XML文件进行解析,这个是一样的。因为有事情,这个写的包括一些方法的命名可能不是怎么规则,还请多多谅解。

  如果代码中有什么错误,欢迎指正!

继续阅读