Android SAX操作xml

来源:互联网 发布:linux get请求url 编辑:程序博客网 时间:2024/06/05 10:32

在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代码如下:

  1. <?xml version="1.0" ?>
  2. <xml_api_reply version="1">
  3.     <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1"
  4.         row="0" section="0">
  5.         <forecast_information>
  6.             <city data="Beijing, Beijing" />
  7.             <postal_code data="beijing" />
  8.             <latitude_e6 data="" />
  9.             <longitude_e6 data="" />
  10.             <forecast_date data="2010-12-27" />
  11.             <current_date_time data="2010-12-28 04:00:00 +0000" />
  12.             <unit_system data="SI" />
  13.         </forecast_information>
  14.         <current_conditions>
  15.             <condition data="晴" />
  16.             <temp_f data="28" />
  17.             <temp_c data="-2" />
  18.             <humidity data="湿度: 27%" />
  19.             <icon data="/ig/images/weather/sunny.gif" />
  20.             <wind_condition data="风向: 西北、风速:7 米/秒" />
  21.         </current_conditions>
  22.         <forecast_conditions>
  23.             <day_of_week data="周一" />
  24.             <low data="-12" />
  25.             <high data="6" />
  26.             <icon data="/ig/images/weather/sunny.gif" />
  27.             <condition data="晴" />
  28.         </forecast_conditions>
  29.         <forecast_conditions>
  30.             <day_of_week data="周二" />
  31.             <low data="-11" />
  32.             <high data="1" />
  33.             <icon data="/ig/images/weather/sunny.gif" />
  34.             <condition data="晴" />
  35.         </forecast_conditions>
  36.         <forecast_conditions>
  37.             <day_of_week data="周三" />
  38.             <low data="-11" />
  39.             <high data="2" />
  40.             <icon data="/ig/images/weather/chance_of_snow.gif" />
  41.             <condition data="可能降雪" />
  42.         </forecast_conditions>
  43.         <forecast_conditions>
  44.             <day_of_week data="周四" />
  45.             <low data="-13" />
  46.             <high data="-2" />
  47.             <icon data="/ig/images/weather/sunny.gif" />
  48.             <condition data="晴" />
  49.         </forecast_conditions>
  50.     </weather>
  51. </xml_api_reply>
复制代码
不同时间可能获取到的不同,但是格式应该是一致的!下面是根据这个抽象出来的类:
  1. package com.SAXXMLReader;

  2. public class NowWeather {
  3.     private String condition;
  4.     private String temp_f;
  5.     private String temp_c;
  6.     private String humidity;
  7.     private String icon;
  8.     private String wind_condition;

  9.     public NowWeather() {

  10.     }

  11.     public void setcondition(String condition) {
  12.         this.condition = condition;
  13.     }

  14.     public void settempf(String temp_f) {
  15.         this.temp_f = temp_f;
  16.     }

  17.     public void settempc(String temp_c) {
  18.         this.temp_c = temp_c;
  19.     }

  20.     public void sethumidity(String humidity) {
  21.         this.humidity = humidity;
  22.     }

  23.     public void seticon(String icon) {
  24.         this.icon = icon;
  25.     }

  26.     public void setwindcondition(String wind_condition) {
  27.         this.wind_condition = wind_condition;
  28.     }

  29.     public String getNowWeather()
  30.     {
  31.         StringBuilder strBuilder = new StringBuilder();
  32.         strBuilder.append(condition+"\n");
  33.         strBuilder.append(temp_f+"\n");
  34.         strBuilder.append(temp_c+"\n");
  35.         strBuilder.append(humidity+"\n");
  36.         strBuilder.append(icon+"\n");
  37.         strBuilder.append(wind_condition+"\n");
  38.         
  39.         return strBuilder.toString();
  40.     }
  41. }
复制代码
这个类保存的是获取到的数据,形式可能有多种,这个根据个人的习惯进行书写吧。写到这里,因为在SAX中使用的时候需要有一个DefaultHandler类的继承,实现如下:
  1. package com.SAXXMLReader;

  2. import org.xml.sax.Attributes;
  3. import org.xml.sax.SAXException;
  4. import org.xml.sax.helpers.DefaultHandler;

  5. import android.util.Log;

  6. public class WeatherHandler extends DefaultHandler {

  7.     private final String CURRENT_CONDITIONS = "current_conditions"; // 当前
  8.     private final String forecast_conditions = "forecast_conditions"; // 当前
  9.     // 实时天气信息
  10.     private boolean is_Current_Conditions = false;
  11.     // 预报天气信息
  12.     private boolean is_Forecast_Conditions = false;
  13.     NowWeather nowWeather = new NowWeather();
  14.     @Override
  15.     public void characters(char[] ch, int start, int length)
  16.             throws SAXException {
  17.         // TODO Auto-generated method stub
  18.         super.characters(ch, start, length);
  19.     }

  20.     @Override
  21.     public void startDocument() throws SAXException {
  22.         // TODO Auto-generated method stub
  23.         super.startDocument();
  24.     }

  25.     public WeatherHandler() {

  26.     }
  27.     @Override
  28.     public void startElement(String uri, String localName, String qName,
  29.             Attributes attributes) throws SAXException {
  30.         // TODO Auto-generated method stub
  31.         // super.startElement(uri, localName, qName, attributes);
  32.         String dataAttribute = "OK";
  33.         // Log.d("WeatherHandler", localName);

  34.         if (localName.equals(CURRENT_CONDITIONS)) {
  35.             Log.d("WeatherHandler", localName);
  36.             is_Current_Conditions = true;
  37.         } else if (localName.equals(forecast_conditions)) {
  38.             is_Current_Conditions = false;
  39.         } else {
  40.             dataAttribute = attributes.getValue("data");
  41.             if (this.is_Current_Conditions) {

  42.                 Log.d("WeatherHandler_1", dataAttribute);
  43.             //    this.nowWeather.setcondition(dataAttribute);
  44.                 if (localName.equals("condition")) {
  45.                     this.nowWeather.setcondition(dataAttribute);
  46.                 } else if (localName.equals("temp_f")) {
  47.                     this.nowWeather.settempf(dataAttribute);
  48.                 } else if (localName.equals("temp_c")) {
  49.                     this.nowWeather.settempc(dataAttribute);
  50.                 } else if (localName.equals("humidity")) {
  51.                     this.nowWeather.sethumidity(dataAttribute);
  52.                 } else if (localName.equals("icon")) {
  53.                     this.nowWeather.seticon(dataAttribute);
  54.                 } else if (localName.equals("wind_condition")) {
  55.                     this.nowWeather.setwindcondition(dataAttribute);
  56.                 }
  57.             } else if (this.is_Forecast_Conditions) {
  58.                 Log.d("WeatherHandler_1", dataAttribute);
  59.             }

  60.         }
  61.         // Log.d("WeatherHandler_1", dataAttribute);
  62.     }

  63.     public String getNowWeather() {
  64.         return nowWeather.getNowWeather();
  65.     }

  66.     @Override
  67.     public void endDocument() throws SAXException {
  68.         // TODO Auto-generated method stub
  69.         super.endDocument();
  70.     }

  71.     @Override
  72.     public void endElement(String uri, String localName, String name)
  73.             throws SAXException {
  74.     }
  75. }
复制代码
在这里实现了读取XML代码,并且保存到抽象出来的类中,以供调用。下面的方法是对这个类的调用,通过调用,获取内容:
  1. SAXParserFactory faction =SAXParserFactory.newInstance();
  2. SAXParser parser = faction.newSAXParser();
  3. WeatherHandler handler = new WeatherHandler();

  4. XMLReader reader = parser.getXMLReader();

  5. reader.setContentHandler(handler);

  6. URL url = new URL(SRC);

  7. HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
  8. //httpconn.getInputStream();

  9. InputStream inStream =httpconn.getInputStream();// this.getResources().openRawResource(R.xml.weather);
  10. InputStreamReader isReader = new InputStreamReader(inStream,"GBK");
  11. //BufferedReader buffRreader = new BufferedReader(isReader);
  12. //String line="";
  13. //String data = "";
  14. //
  15. //while((line=buffRreader.readLine())!=null)
  16. //    data += line;
  17. //text1.setText(data);
  18. //Toast.makeText(this,data, Toast.LENGTH_LONG).show();
  19. InputSource inputSource = new InputSource(isReader);
  20. reader.parse(inputSource);
  21. text1.setText(handler.getNowWeather());
  22. //Toast.makeText(this, handler.getNowWeather(), Toast.LENGTH_LONG).show();
复制代码
这里直接通过获取网上的XML进行的解析,当然你也可以读取本地的XML文件进行解析,这个是一样的。因为有事情,这个写的包括一些方法的命名可能不是怎么规则,还请多多谅解。  如果代码中有什么错误,欢迎指正!
原创粉丝点击