Android学习笔记——SAX解析XML

XML数据源:

<?xml version="1.0" encoding="utf-8"?><WeatherWindow>    <updated>2015-09-08 20:00:00</updated>    <region><![CDATA[上海]]></region>    <today>        <condition><![CDATA[晴转多云]]></condition>        <temphigh>29</temphigh>        <templow>22</templow>        <image_url><![CDATA[http://media.lily.tvxio.com/icons/duoyun.png]]></image_url>    </today>    <tomorrow>        <condition><![CDATA[多云]]></condition>        <temphigh>29</temphigh>        <templow>29</templow>        <image_url><![CDATA[http://media.lily.tvxio.com/icons/duoyun.png]]></image_url>    </tomorrow></WeatherWindow>

定义实体类:

package tv.ismar.daisy.data.weather;

/** * Created by <huaijiefeng@gmail.com> on 9/15/14. */public class WeatherEntity {    private String updated;    private String region;

   private WeatherDetail today;    private WeatherDetail tomorrow;

   public String getUpdated() {        return updated;    }

   public void setUpdated(String updated) {        this.updated = updated;    }

   public String getRegion() {        return region;    }

   public void setRegion(String region) {        this.region = region;    }

   public WeatherDetail getToday() {        return today;    }

   public void setToday(WeatherDetail today) {        this.today = today;    }

   public WeatherDetail getTomorrow() {        return tomorrow;    }

   public void setTomorrow(WeatherDetail tomorrow) {        this.tomorrow = tomorrow;    }

   public static class WeatherDetail {

       private String condition;        private String temphigh;        private String templow;        private String image_url;

       public String getCondition() {            return condition;        }

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

       public String getTemphigh() {            return temphigh;        }

       public void setTemphigh(String temphigh) {            this.temphigh = temphigh;        }

       public String getTemplow() {            return templow;        }

       public void setTemplow(String templow) {            this.templow = templow;        }

       public String getImage_url() {            return image_url;        }

       public void setImage_url(String image_url) {            this.image_url = image_url;        }

   }}

解析XML:

package tv.ismar.daisy.core.weather;

import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import tv.ismar.daisy.data.weather.WeatherEntity;

/** * Created by huaijie on 9/15/15. */public class WeatherInfoHandler extends DefaultHandler {

   private final int TODAY = 5;    private final int TOMORROW = 6;

   private final int UPDATED = 7;    private final int REGION = 8;

   private final int CONDITION = 1;    private final int TEMPHIGH = 2;    private final int TEMPLOW = 3;    private final int IMAGE_URL = 4;

   private int flg = 0;

   private WeatherEntity weatherEntity;    private WeatherEntity.WeatherDetail weatherDetail;

   public WeatherEntity getWeatherEntity() {        return weatherEntity;    }

   @Override    public void startDocument() throws SAXException {        weatherEntity = new WeatherEntity();    }

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

   @Override    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {        if (localName.equals("WeatherWindow")) {            flg = 0;            return;        }

       if (localName.equals("updated")) {            flg = UPDATED;            return;        }

       if (localName.equals("region")) {            flg = REGION;            return;        }

       if (localName.equals("today")) {            weatherDetail = new WeatherEntity.WeatherDetail();            flg = TODAY;            return;        }

       if (localName.equals("tomorrow")) {            weatherDetail = new WeatherEntity.WeatherDetail();            flg = TOMORROW;            return;        }

       if (localName.equals("condition")) {            flg = CONDITION;            return;        }

       if (localName.equals("temphigh")) {            flg = TEMPHIGH;            return;        }

       if (localName.equals("templow")) {            flg = TEMPLOW;            return;        }

       if (localName.equals("image_url")) {            flg = IMAGE_URL;            return;        }

   }

   @Override    public void endElement(String uri, String localName, String qName) throws SAXException {        if (localName.equals("today")) {            weatherEntity.setToday(weatherDetail);            weatherDetail = null;            return;        }

       if (localName.equals("tomorrow")) {            weatherEntity.setTomorrow(weatherDetail);            weatherDetail = null;            return;        }    }

   @Override    public void characters(char[] ch, int start, int length) throws SAXException {        String str = new String(ch, start, length);

       switch (flg) {            case UPDATED:                weatherEntity.setUpdated(str);                break;            case REGION:                weatherEntity.setRegion(str);                break;            case CONDITION:                weatherDetail.setCondition(str);                break;            case TEMPHIGH:                weatherDetail.setTemphigh(str);                break;            case TEMPLOW:                weatherDetail.setTemplow(str);                break;            case IMAGE_URL:                weatherDetail.setImage_url(str);                break;            default:                return;        }    }}

运行:

SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();try {    SAXParser saxParser = saxParserFactory.newSAXParser();    XMLReader xmlReader = saxParser.getXMLReader();    WeatherInfoHandler weatherInfoHandler = new WeatherInfoHandler();    xmlReader.setContentHandler(weatherInfoHandler);    InputSource inputSource = new InputSource(new StringReader(result));    xmlReader.parse(inputSource);

   WeatherEntity weatherEntity = weatherInfoHandler.getWeatherEntity();

   Log.i(TAG, "update: " + weatherEntity.getUpdated() + " region: " + weatherEntity.getRegion());    Log.i(TAG, "today condition: " + weatherEntity.getToday().getCondition());    Log.i(TAG, "today temphigh: " + weatherEntity.getToday().getTemphigh());    Log.i(TAG, "today templow: " + weatherEntity.getToday().getTemplow());    Log.i(TAG, "today image_url: " + weatherEntity.getToday().getImage_url());

   Log.i(TAG, "tomorrow condition: " + weatherEntity.getTomorrow().getCondition());    Log.i(TAG, "tomorrow temphigh: " + weatherEntity.getTomorrow().getTemphigh());    Log.i(TAG, "tomorrow templow: " + weatherEntity.getTomorrow().getTemplow());    Log.i(TAG, "tomorrow image_url: " + weatherEntity.getTomorrow().getImage_url());

   todayWeatherTemperature.setText(weatherEntity.getToday().getTemplow() + "℃ ~ " + weatherEntity.getToday().getTemphigh() + "℃");    todayWeatherInfo.setText(weatherEntity.getToday().getCondition());    Picasso.with(mContext).load(weatherEntity.getToday().getImage_url()).into(todayWeatherIcon1);

   tomorrowWeatherTemperature.setText(weatherEntity.getTomorrow().getTemplow() + "℃ ~ " + weatherEntity.getTomorrow().getTemphigh() + "℃");    tomorrowWeatherInfo.setText(weatherEntity.getTomorrow().getCondition());    Picasso.with(mContext).load(weatherEntity.getToday().getImage_url()).into(tomorrowWeatherIcon1);

} catch (ParserConfigurationException e) {    e.printStackTrace();} catch (SAXException e) {    e.printStackTrace();} catch (IOException e) {    e.printStackTrace();}
时间: 2024-08-01 14:33:40

Android学习笔记——SAX解析XML的相关文章

Android 学习之pull解析Xml

一. PUll解析Xml public static List<Person> xmlParser(InputStream xml) throws Exception { List<Person> persons=null; Person p=null; XmlPullParser parser=Xml.newPullParser(); parser.setInput(xml, "UTF-8"); int event=parser.getEventType();

Android 使用pull,sax解析xml

pull解析xml文件 1.获得XmlpullParser类的引用 这里有两种方法 //解析器工厂 XmlPullParserFactory factory=XmlPullParserFactory.newInstance(); XmlPullParser pullParser=factory.newPullParser(); //直接获得实例XmlPullParser pullParser= Xml.newPullParser(); 2.设置解析内容 通过setInput方法设置解析内容  

javaSE学习笔记SAX解析(6)

SAX即Simple Api for Xml就是一个简单的操作XML数据的一套SUN提供的API机制. SAX采用的解析的原理是基于事件触发的机制. SAX技术只能进行XML数据的读取. 1.准备需要解析的XML文件linkmans.xml<?xml version="1.0" encoding="UTF-8" standalone="no"?> <linkmans> <linkman> <name>

Android学习笔记之AndroidManifest.xml文件解析

一.关于AndroidManifest.xml AndroidManifest.xml 是每个android程序中必须的文件.它位于整个项目的根目录,描述了package中暴露的组件(activities, services, 等等),他们各自的实现类,各种能被处理的数据和启动位置. 除了能声明程序中的Activities, ContentProviders, Services, 和Intent Receivers,还能指定permissions和instrumentation(安全控制和测试)

[转载] Android学习笔记之AndroidManifest.xml文件解析

一.关于AndroidManifest.xml AndroidManifest.xml 是每个android程序中必须的文件.它位于整个项目的根目录,描述了package中暴露的组件(activities, services, 等等),他们各自的实现类,各种能被处理的数据和启动位置. 除了能声明程序中的Activities, ContentProviders, Services, 和Intent Receivers,还能指定permissions和instrumentation(安全控制和测试)

Android学习笔记之AndroidManifest.xml文件解析(转)

//自已备注: <?xml version="1.0" encoding="utf-8"?>//说明了版本号,字符集 <manifest xmlns:android="http://schemas.android.com/apk/res/android"//定义android命名空间 package="com.example.helloworld"//包名 android:versionCode="

Android学习笔记之AndroidManifest.xml文件解析【转载地址:http://www.cnblogs.com/pilang/archive/2011/04/20/2022932.html】

一.关于AndroidManifest.xml AndroidManifest.xml 是每个android程序中必须的文件.它位于整个项目的根目录,描述了package中暴露的组件(activities, services, 等等),他们各自的实现类,各种能被处理的数据和启动位置. 除了能声明程序中的Activities, ContentProviders, Services, 和Intent Receivers,还能指定permissions和instrumentation(安全控制和测试)

Android学习笔记(四五):互联网通信-HttpClient、XML解析(W3C)

前几日Android发布了4.0 Icecream,昨天上网发现Begining Book中有Edition 3的版本,比对一下,还是有相当的改动,不仅仅增加了tablet的部分,对原有的章节有有一些修订,前后的调整等等.先按Edtion 2的顺序看,相同章节的看Edtion 3,然后回头看Edition 3的Chapter 24.25(E2的36).26.27.28.29.44.45.46.47几个新增章节.同时将模拟器改为Android 2.3的版本,已适应可能新增的改动. 访问Intern

android学习二十二(使用SAX解析xml)

上一篇博客是使用Pull解析xml文件的,Pull解析方式虽然非常好用,但它并不是我们唯一的选择.SAX解析也是一种特别常用的XML解析方式,虽然它的用法比Pull解析复杂,但在语义方面会更加的清楚. 通常情况下我们都会新建一个类继承自DefaultHandler,并重写父类的五个方法,如下所示: package com.jack.networktest; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import