1. 程式人生 > >安卓下如何使用XmlPullParser解析xml檔案並顯示在TextView控制元件上

安卓下如何使用XmlPullParser解析xml檔案並顯示在TextView控制元件上

解析xml檔案有好多種方式,今天介紹下XmlPullParser怎麼解析xml檔案,既然是要解析xml檔案首先得需要一個xml檔案

如下weather.xml檔案

<?xml version="1.0" encoding="utf-8"?>
<weather>
    <channel id="1">
        <city>北京</city>
        <temp>25℃</temp>
        <wind>3</wind>
        <pm250>300</pm250>
    </channel>
    <channel id="2">
        <city>江西</city>
        <temp>30℃</temp>
        <wind>4</wind>
        <pm250>200</pm250>
    </channel>
    <channel id="3">
        <city>湖北</city>
        <temp>30℃</temp>
        <wind>2</wind>
        <pm250>300</pm250>
    </channel>
    <channel id="4">
        <city>杭州</city>
        <temp>30℃</temp>
        <wind>4</wind>
        <pm250>200</pm250>
    </channel>
</weather>
然後有個與之對應的類Channel.java,程式碼如下

package com.example.xmlparser;

/**
 * Created by Administrator on 2016-06-21.
 */
public class Channel {
    private String id;
    private String city;
    private String temp;
    private String wind;
    private String pm250;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getTemp() {
        return temp;
    }

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

    public String getWind() {
        return wind;
    }

    public void setWind(String wind) {
        this.wind = wind;
    }

    public String getPm250() {
        return pm250;
    }

    public void setPm250(String pm250) {
        this.pm250 = pm250;
    }

    @Override
    public String toString() {
        return "Channel[id="+id +",city="+ city +",temp="+ temp +"" +
                ",wind="+ wind +",pm250="+ pm250 +"]";
    }
}

然後main_actiity.xml檔案中程式碼如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.xmlparser.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/tv_weather"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

然後在Weather.java中解析xml檔案(重點邏輯都在這一段)

package com.example.xmlparser;

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

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

/**
 * Created by Administrator on 2016-06-21.
 */
public class Weather {
    /**
     * 伺服器是以流的形式吧資料返回
     */
    public static List<Channel> parserXml(InputStream in)throws Exception{
        //0.宣告集合物件
        List<Channel> weatherLists = null;
        Channel channel = null;
        //1.獲取xmlpullparser解析例項
        XmlPullParser parser = Xml.newPullParser();
        //2.設定XmlPullParser的引數
        parser.setInput(in,"utf-8");
        //3.獲取時間型別
        int type = parser.getEventType();
        while (type!=XmlPullParser.END_DOCUMENT){

            switch (type){
                //4.具體判斷下解析到了哪個開始標籤
                case XmlPullParser.START_TAG://開始解析標籤
                    if ("weather".equals(parser.getName())){
                        //5.建立一個集合物件
                        weatherLists = new ArrayList<Channel>();
                    }else if ("channel".equals(parser.getName())){
                        //6.建立Channel物件
                        channel = new Channel();
                        //7.獲取id值
                        String id = parser.getAttributeName(0);
                        channel.setId(id);
                    }else if ("city".equals(parser.getName())){
                        //9.獲取city值
                        String city = parser.nextText();
                        channel.setCity(city);
                    }else if ("temp".equals(parser.getName())){
                        //10.獲取temp值
                        String temp = parser.nextText();
                        channel.setCity(temp);
                    } else if ("wind".equals(parser.getName())){
                        //11.獲取wind值
                        String wind = parser.nextText();
                        channel.setCity(wind);
                    }else if ("pm250".equals(parser.getName())){
                        //12.獲取pm250值
                        String pm250 = parser.nextText();
                        channel.setCity(pm250);
                    }

                    break;
                case XmlPullParser.END_TAG:  //解析結束標誌
                    //判斷要解析的結束標籤
                    if ("channel".equals(parser.getName())){
                        //把javabean物件存到集合中
                        weatherLists.add(channel);
                    }

            }

            //不停的向下解析
            type = parser.next();
        }

        return  weatherLists;
    }

}
最後是MainActivity.java,程式碼如下

package com.example.xmlparser;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;


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


public class MainActivity extends AppCompatActivity {

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

        try {
            //1.顯示天氣資訊
            TextView tv = (TextView) findViewById(R.id.tv_weather);
            //1.1獲取資產管理者,通過上下文
            InputStream inputStream = getResources().getAssets().open("weather.xml");
            //2.呼叫我們定義的解析xml業務方法

            List<Channel> weather = Weather.parserXml(inputStream);
            StringBuffer sb = new StringBuffer();
            for (Channel channel : weather) {
              sb.equals(channel.toString());
            }
            //3.把資料展示到textview上
            tv.setText(inputStream.toString());
        }catch (Exception e){
            e.printStackTrace();
        }


    }

}

這樣就解析好了