安卓下如何使用XmlPullParser解析xml文件并显示在TextView控件上

这篇博客介绍了如何在Android环境下使用XmlPullParser解析xml文件,并将解析后的数据展示在TextView上。通过示例展示了从读取xml文件到创建解析器,解析weather.xml文件中的城市天气信息,以及将数据填充到Channel对象并最终显示的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解析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();
        }


    }

 

}

这样就解析好了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值