码迷,mamicode.com
首页 > 移动开发 > 详细

Android开发学习---使用XmlPullParser解析xml文件

时间:2014-06-05 13:43:09      阅读:378      评论:0      收藏:0      [点我收藏+]

标签:android   c   style   class   blog   code   

Android中解析XML的方式主要有三种:sax,dom和pull关于其内容可参考:http://blog.csdn.net/liuhe688/article/details/6415593

本文将主要介绍pull解析器解析xml文件,环境为ubuntu 12.04+ intelij 13.1 + android sdk 2.1

一.创建一个XML项目,步骤如下:

bubuko.com,布布扣

 

bubuko.com,布布扣

 

bubuko.com,布布扣

 

 

二.解析一个xml文件:

assets/person.xml

bubuko.com,布布扣
<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1101">
        <name>amos</name>
        <age>30</age>
    </person>
    <person id="1102">
        <name>tom</name>
        <age>18</age>
    </person>
</persons>
bubuko.com,布布扣

com/amos/xml/domain/Person.java

bubuko.com,布布扣
package com.amos.xml.domain;

/**
 * Created by amosli on 14-6-3.
 */

public class Person {
    private String name;
    private Integer age;
    private Integer id;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        if (age < 1 || age > 100) {
            this.age = 0;
        } else {
            this.age = age;
        }
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {

        return name;

    }

    public void setName(String name) {
        this.name = name;
    }
}
bubuko.com,布布扣

 

com/amos/xml/service/PersonService.java

bubuko.com,布布扣
package com.amos.xml.service;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import android.util.Xml;
import com.amos.xml.domain.Person;
import org.xmlpull.v1.XmlPullParser;

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

/**
 * Created by amosli on 14-6-3.
 */
public class PersonService {
    private Context context;

    public PersonService(Context context) {
        this.context = context;
    }

    /**
     * 把person.xml的输入流解析转化成list集合
     *
     * @param
     * @return
     */
    public List<Person> getPersons(String filename) {

        AssetManager manager = context.getAssets();
        //初始化项目.
      List<Person> persons = null;
        Person person = null;

        try {
            InputStream inputStream = manager.open(filename);
            //在android下使用xmlpullparser进行解析
            XmlPullParser xmlPullParser = Xml.newPullParser();
            //设置xmlpullparser的一些参数
            xmlPullParser.setInput(inputStream, "utf-8");

            //获取pull解析器对应事件类型
            int eventType = xmlPullParser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        persons = new ArrayList<Person>();
                        break;

                    case XmlPullParser.START_TAG:
                        if (xmlPullParser.getName().equals("person")) {
                            person = new Person();
                            String id = xmlPullParser.getAttributeValue(0);
                            Log.d("person.id", id);
                            person.setId(Integer.parseInt(id));
                            eventType = xmlPullParser.next();
                        } else if (xmlPullParser.getName().equals("name")) {
                            String name = xmlPullParser.nextText();
                            Log.d("person.name", name);
                            person.setName(name);
                            eventType = xmlPullParser.next();
                        } else if (xmlPullParser.getName().equals("age")) {
                            String age = xmlPullParser.nextText();
                            Log.d("person.age", age);
                            person.setAge(Integer.valueOf(age));
                            eventType = xmlPullParser.next();
                        }
                           break;
                    case XmlPullParser.END_TAG:
                        if (xmlPullParser.getName().equals("person")) {
                            persons.add(person);
                            person = null;
                        }
                        break;
                }
                eventType = xmlPullParser.next();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return persons;
    }
}
bubuko.com,布布扣

 注:这里解析主要用到的是eventType(事件类型),如果是START_DOCUMENT则表示读到文档开始位置,如果是START_TAG,则表示读到文档中的元素开始位置,如<name>,类似的结束位置为END_DOCUMENT和END_TAG;其中要注意判断其事件类型开始的名称是什么,并且取值时,注意其不同位置取值方式也不一样,如<person id="1122">,那么取id的方式为getAttributeValue(int index),另外取<name >amos</name>,则要用nextText()方法进行取值.

 

/com/amos/xml/MyActivity.java

bubuko.com,布布扣
package com.amos.xml;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.amos.xml.domain.Person;
import com.amos.xml.service.PersonService;

import java.util.List;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView show_users = (TextView) findViewById(R.id.show_users);
        PersonService personService = new PersonService(this);
        StringBuilder stringBuilder = new StringBuilder();
        List<Person> persons = personService.getPersons("person.xml");
        for (Person person : persons) {
            stringBuilder.append("  " + person.getName()).append(":").append(person.getAge());
        }
        System.out.println("stringBuilder:" + stringBuilder);
        show_users.setText(stringBuilder);
        Toast.makeText(this, "数据写入成功!" + stringBuilder, Toast.LENGTH_LONG);
    }
}
bubuko.com,布布扣

这里我在主界面定义了一个TextView,用来显示读取到的xml文件的内容,效果如下图所示:

bubuko.com,布布扣

 

3.测试用例

首先,加入必要的配置:AndroidManifest.xml

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.amos.xml"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7"/>
    <application android:label="@string/app_name">
        <uses-library android:name="android.test.runner"/>
        <activity android:name="MyActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
    <instrumentation android:name="android.test.InstrumentationTestRunner"
                     android:targetPackage="com.amos.xml"/>

</manifest> 
bubuko.com,布布扣

其中加粗的部分是后加入到项目中的.

其次,写一个testcase:/com/amos/xml/test/TestService.java

bubuko.com,布布扣
package com.amos.xml.test;

import android.test.AndroidTestCase;
import com.amos.xml.domain.Person;
import com.amos.xml.service.PersonService;

import java.util.List;

/**
 * Created by amosli on 14-6-3.
 */
public class TestService extends AndroidTestCase {

    public void testGetPersons() throws Exception {
        PersonService personService = new PersonService(getContext());
        List<Person> persons = personService.getPersons("person.xml");
        for (Person person : persons) {
            System.out.println(person.getName());
        }
    }
}
bubuko.com,布布扣

这里想要查看每一步的运行步骤,可以加上断点,intelij 中的快捷键是F8(step over),F7(step into),F9(Resume program).

本文git 地址:https://github.com/amosli/android_basic/tree/xml

 

 

 

Android开发学习---使用XmlPullParser解析xml文件,布布扣,bubuko.com

Android开发学习---使用XmlPullParser解析xml文件

标签:android   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/amosli/p/3769118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!