在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_replyversion="1">
<weathermodule_id="0"tab_id="0"mobile_row="0"mobile_zipped="1"
row="0"section="0">
<forecast_information>
<citydata="Beijing, Beijing"/>
<postal_codedata="beijing"/>
<latitude_e6data=""/>
<longitude_e6data=""/>
<forecast_datedata="2010-12-27"/>
<current_date_timedata="2010-12-28 04:00:00 +0000"/>
<unit_systemdata="SI"/>
</forecast_information>
<current_conditions>
<conditiondata="晴"/>
<temp_fdata="28"/>
<temp_cdata="-2"/>
<humiditydata="湿度: 27%"/>
<icondata="/ig/images/weather/sunny.gif"/>
<wind_conditiondata="风向: 西北、风速:7 米/秒"/>
</current_conditions>
<forecast_conditions>
<day_of_weekdata="周一"/>
<lowdata="-12"/>
<highdata="6"/>
<icondata="/ig/images/weather/sunny.gif"/>
<conditiondata="晴"/>
</forecast_conditions>
<forecast_conditions>
<day_of_weekdata="周二"/>
<lowdata="-11"/>
<highdata="1"/>
<icondata="/ig/images/weather/sunny.gif"/>
<conditiondata="晴"/>
</forecast_conditions>
<forecast_conditions>
<day_of_weekdata="周三"/>
<lowdata="-11"/>
<highdata="2"/>
<icondata="/ig/images/weather/chance_of_snow.gif"/>
<conditiondata="可能降雪"/>
</forecast_conditions>
<forecast_conditions>
<day_of_weekdata="周四"/>
<lowdata="-13"/>
<highdata="-2"/>
<icondata="/ig/images/weather/sunny.gif"/>
<conditiondata="晴"/>
</forecast_conditions>
</weather>
</xml_api_reply>
不同时间可能获取到的不同,但是格式应该是一致的!
下面是根据这个抽象出来的类:
packagecom.SAXXMLReader;
publicclassNowWeather {
privateString condition;
privateString temp_f;
privateString temp_c;
privateString humidity;
privateString icon;
privateString wind_condition;
publicNowWeather() {
}
publicvoidsetcondition(String condition) {
this.condition=condition;
}
publicvoidsettempf(String temp_f) {
this.temp_f=temp_f;
}
publicvoidsettempc(String temp_c) {
this.temp_c=temp_c;
}
publicvoidsethumidity(String humidity) {
this.humidity=humidity;
}
publicvoidseticon(String icon) {
this.icon=icon;
}
publicvoidsetwindcondition(String wind_condition) {
this.wind_condition=wind_condition;
}
publicString getNowWeather()
{
StringBuilder strBuilder=newStringBuilder();
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");
returnstrBuilder.toString();
}
}
这个类保存的是获取到的数据,形式可能有多种,这个根据个人的习惯进行书写吧。
写到这里,因为在SAX中使用的时候需要有一个DefaultHandler类的继承,实现如下:
packagecom.SAXXMLReader;
importorg.xml.sax.Attributes;
importorg.xml.sax.SAXException;
importorg.xml.sax.helpers.DefaultHandler;
importandroid.util.Log;
publicclassWeatherHandlerextendsDefaultHandler {
privatefinalString CURRENT_CONDITIONS="current_conditions";//当前
privatefinalString forecast_conditions="forecast_conditions";//当前
//实时天气信息
privatebooleanis_Current_Conditions=false;
//预报天气信息
privatebooleanis_Forecast_Conditions=false;
NowWeather nowWeather=newNowWeather();
@Override
publicvoidcharacters(char[] ch,intstart,intlength)
throwsSAXException {
//TODO Auto-generated method stub
super.characters(ch, start, length);
}
@Override
publicvoidstartDocument()throwsSAXException {
//TODO Auto-generated method stub
super.startDocument();
}
publicWeatherHandler() {
}
@Override
publicvoidstartElement(String uri, String localName, String qName,
Attributes attributes)throwsSAXException {
//TODO Auto-generated method stub
//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;
}elseif(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);
}elseif(localName.equals("temp_f")) {
this.nowWeather.settempf(dataAttribute);
}elseif(localName.equals("temp_c")) {
this.nowWeather.settempc(dataAttribute);
}elseif(localName.equals("humidity")) {
this.nowWeather.sethumidity(dataAttribute);
}elseif(localName.equals("icon")) {
this.nowWeather.seticon(dataAttribute);
}elseif(localName.equals("wind_condition")) {
this.nowWeather.setwindcondition(dataAttribute);
}
}elseif(this.is_Forecast_Conditions) {
Log.d("WeatherHandler_1", dataAttribute);
}
}
//Log.d("WeatherHandler_1", dataAttribute);
}
publicString getNowWeather() {
returnnowWeather.getNowWeather();
}
@Override
publicvoidendDocument()throwsSAXException {
//TODO Auto-generated method stub
super.endDocument();
}
@Override
publicvoidendElement(String uri, String localName, String name)
throwsSAXException {
}
}
在这里实现了读取XML代码,并且保存到抽象出来的类中,以供调用。
下面的方法是对这个类的调用,通过调用,获取内容:
SAXParserFactory faction=SAXParserFactory.newInstance();
SAXParser parser=faction.newSAXParser();
WeatherHandler handler=newWeatherHandler();
XMLReader reader=parser.getXMLReader();
reader.setContentHandler(handler);
URL url=newURL(SRC);
HttpURLConnection httpconn=(HttpURLConnection) url.openConnection();
//httpconn.getInputStream();
InputStream inStream=httpconn.getInputStream();//this.getResources().openRawResource(R.xml.weather);
InputStreamReader isReader=newInputStreamReader(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=newInputSource(isReader);
reader.parse(inputSource);
text1.setText(handler.getNowWeather());
//Toast.makeText(this, handler.getNowWeather(), Toast.LENGTH_LONG).show();
这里直接通过获取网上的XML进行的解析,当然你也可以读取本地的XML文件进行解析,这个是一样的。因为有事情,这个写的包括一些方法的命名可能不是怎么规则,还请多多谅解。
1 条评论
samool你好,请问如何掌握android的sdk中的各个函数,及其作用呢