android使用pull解析器来解析和生成xml文件

解析xml文件的方式有多种,比如SAX解析,DOM解析,PULL解析,但是在android中推荐使用pull解析方式来解析xml文件
pull解析器使用实验代码:
Person.java

package com.dqpi.model;

public class Person {

    private Integer id;
    private String name;
    private Integer 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;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
    public Person(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Person() {
        super();
    }

}

PersonService.java

package com.dqpi.service;

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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import com.dqpi.model.Person;

import android.util.Xml;
/** * 使用pull解析器对person.xml文件进行解析 * @author Administrator * */
public class PersonService {

    /** * 使用pull解析器解析xml文件 * @param xml要解析的xml文件 * @return返回解析的内容 * @throws Exception抛出的异常 */
    public static List<Person> getPersons(InputStream xml) throws Exception {
        //用来存储解析的内容
        List<Person> persons = null;
        //用来设置person属性内容
        Person person = null;
        // 创建pull解析器的对象
        XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
        // 为pull解析器设置解析的xml数据
        pullParser.setInput(xml, "UTF-8");
        // 获取开始节点
        int event = pullParser.getEventType();
        //当没有解析到XML文件的末尾的时候继续执行解析
        while (event != XmlPullParser.END_DOCUMENT) {
            switch (event) {
            case XmlPullParser.START_DOCUMENT:
                //对persons 和person进行初始化
                persons = new ArrayList<Person>();

                break;
            case XmlPullParser.START_TAG:
                if ("person".equals(pullParser.getName())) {
                    int id = new Integer(pullParser.getAttributeValue(0));
                    person = new Person();
                    person.setId(id);
                }
                if ("name".equals(pullParser.getName())) {
                    String name = pullParser.nextText();
                    person.setName(name);
                }
                if ("age".equals(pullParser.getName())) {
                    int age = new Integer(pullParser.nextText());
                    person.setAge(age);
                }
                break;
            case XmlPullParser.END_TAG:
                if ("person".equals(pullParser.getName())) {
                    persons.add(person);
                    person = null;
                }
                break;
            }
            //触发下一个节点
            event = pullParser.next();
        }
        return persons;
    }
    /** * 生成xml文件 * @param persons生成xml的件的数据来源 * @param outputStream文件输出的对象 * @throws Exception抛出的异常 */
    public static void save(List<Person> persons,OutputStream outputStream)throws Exception{
        XmlSerializer serializer = Xml.newSerializer();
        //设置输出的方向
        serializer.setOutput(outputStream, "UTF-8");
        //开始文档
        serializer.startDocument("UTF-8", true);
        //文档开始节点
        serializer.startTag(null, "persons");
        for(Person person:persons){
            //person
            serializer.startTag(null, "person");
            serializer.attribute(null, "id", person.getId().toString());

            //name
            serializer.startTag(null, "name");
            serializer.text(person.getName());
            serializer.endTag(null, "name");

            //age
            serializer.startTag(null, "age");
            serializer.text(person.getAge().toString());
            serializer.endTag(null, "age");
            serializer.endTag(null, "person");
        }
        //文档结束节点
        serializer.endTag(null, "persons");
        //结束文档
        serializer.endDocument();
        //把数据刷出去
        outputStream.flush();
        //关闭
        outputStream.close();
    }

}

PersonServiceTest.java

package com.dqpi.test;

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

import com.dqpi.model.Person;
import com.dqpi.service.PersonService;

import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase {

    private static final String TAG="PersonServiceTest";

    public void testPersons()throws Exception{
        InputStream xml = this.getClass().getClassLoader().getResourceAsStream("person.xml");
        List<Person> persons = PersonService.getPersons(xml);
        for(Person person:persons){
            Log.i(TAG, person.toString());
        }
    } 

    public void testSave()throws Exception{
        List<Person> persons = new ArrayList<Person>();
        persons.add(new Person(1,"张三",14));
        persons.add(new Person(2,"李四",15));
        persons.add(new Person(2,"赵六",20));
        //存储在<包名>/file
        File xmlFile = new File(getContext().getFilesDir(),"dqpi.xml");
        FileOutputStream outputStream = new FileOutputStream(xmlFile);
        PersonService.save(persons, outputStream);
    } 
}

person.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="23">
        <name>liming</name>
        <age>30</age>
     </person>
    <person id="20">
        <name>zhangsan</name>
        <age>20</age>
     </person>
</persons>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dqpi.xml" android:versionCode="1" android:versionName="1.0" >
    <uses-sdk  android:minSdkVersion="14" android:targetSdkVersion="22" />
    <application  android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <uses-library android:name="android.test.runner"/>
        <activity  android:name=".MainActivity" 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:label="Tests for My App" android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.dqpi.xml" />
</manifest>

你可能感兴趣的:(android,xml,pull)