pull解析xml文件

在网络上传输数据时候,最常用的就格式有两种,XML和JSON。这里我们来学学如何对XML文件进行解析。

准备工作:在src文件夹下新建一个weater.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<weather>
    <city>
        <name>深圳</name>
        <temp>23°</temp>
        <pm>20</pm>
    </city>
     <city>
        <name>广州</name>
        <temp>24°</temp>
        <pm>25</pm>
    </city>
     <city>
        <name>北京</name>
        <temp></temp>
        <pm>200</pm>
    </city>
     <city>
        <name>上海</name>
        <temp>23°</temp>
        <pm>20</pm>
    </city>
     <city>
        <name>成都</name>
        <temp>23°</temp>
        <pm>20</pm>
    </city>
     <city>
        <name>天津</name>
        <temp>23°</temp>
        <pm>20</pm>
    </city>
</weather>

 

 

 接下来我们要写的程序就是去解析weater.xml里面的信息。

先看看运行截图吧。点击按钮后就会解析出xml文件的信息。

 

 然后我们看布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.pulldemo.MainActivity" >

    <Button
        android:id="@+id/bt_pull"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="pullweater"
        android:text="解析天气信息" />
    
    <TextView 
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        />



</LinearLayout>

 

然后是java文件

首先是javabean City.java

package com.example.pulldemo;

public class City {

    private String name;
    private String temp;
    private String pm;

    public City() {
        super();
        this.name = name;
        this.temp = temp;
        this.pm = pm;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTemp() {
        return temp;
    }

    public void setTemp(String temp) {
        this.temp = temp;
    }

    public String getPm() {
        return pm;
    }

    public void setPm(String pm) {
        this.pm = pm;
    }

    @Override
    public String toString() {
        return "City [name=" + name + ", temp=" + temp + ", pm=" + pm + "]";
    }

}

 

然后是MainActivity.java

package com.example.pulldemo;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    List<City> citylist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
    
    }

    public void pullweater(View v) throws IOException {
        // 拿到src文件夹下的weathet.xml文件,用一个输出流来接收
        InputStream is = getClassLoader().getResourceAsStream("weather.xml");

        // 拿到pull解析器
        XmlPullParser xp = Xml.newPullParser();

        try {
            City c = null;
            // 初始化
            xp.setInput(is, "UTF-8");
            /*
             * xp.getEventType()有几种类型,用数字0,1,2,3,4表示
             * 具体可以ctrl+点击XmlPullParser去查看源代码 例如:int START_DOCUMENT = 0;表示解析到文档头
             * int END_DOCUMENT = 1;表示文档结束
             */
            // 获取当前结点的类型,通过对结点类型的判断,我么可以知道要做什么操作
            int type = xp.getEventType();
            // 如果结点类型不是结束xp.END_DOCUMENT,我们就不断解析
            while (type != XmlPullParser.END_DOCUMENT) {

                switch (type) {
                // 如果解析到开始结点,我们就根据结点名称继续进行判断
                case XmlPullParser.START_TAG:
                    /*
                     * 如果该结点的名称等于weather,也就是这时候我们可以new一个 citylist来存放城市集合
                     */
                    if (xp.getName().equals("weather")) {
                        citylist = new ArrayList<City>();
                    } else if (xp.getName().equals("city")) {
                        // new 一个city来存放天气信息
                        c = new City();
                    } else if (xp.getName().equals("name")) {
                        /*
                         * 获取当前结点的下一个结点文本,为什么是下一个节点?
                         * 因为当前结点名称是name啊!哈哈。<name>北京</name>
                         * 如上面例子,北京才是我们要的文本。所以是下一个结点
                         */
                        String name = xp.nextText();
                        c.setName(name);
                    } else if (xp.getName().equals("temp")) {
                        String temp = xp.nextText();
                        c.setTemp(temp);
                    } else if (xp.getName().equals("pm")) {
                        String pm = xp.nextText();
                        c.setPm(pm);
                    }

                    break;
                case XmlPullParser.END_TAG:
                    /*如果解析到city的结束结点,说明一个城市的信息解析完了。将其
                     * 封装到集合中就可以了
                    */
                    if(xp.getName().equals("city")){
                       citylist.add(c);
                    }

                default:
                    break;
                }
                //移动指针到下一个节点,并返回该结点的值
                type = xp.next();
            }
            StringBuffer sb = new StringBuffer();
            for (City city : citylist) {
                //System.out.println(city.toString());
                sb.append(city.toString()+"\n"+"\n");
            }
            //拿到显示信息的TextView
            TextView tv ;
            tv = (TextView) findViewById(R.id.tv);
            tv.setText(sb.toString());
            Toast.makeText(this, "解析完毕", 0).show();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            is.close();
        }
    }

}

 

重要的点,我都在代码中有注释。看注释应该就明白了。 

 

posted @ 2016-04-15 15:51  _Vincent  阅读(271)  评论(0编辑  收藏  举报