Pull解析XML文件

PULL解析器的运行方式是基于事件的解析模式。在PULL解析过程中,我们需要自己获取产生的事件然后做相应的操作。PULL解析器小巧轻便,解析速度快,简单易用,非常适合在Android移动设备中使用,Android系统内部在解析各种XML时也是用PULL解析器。

Demo链接:http://download.csdn.net/detail/l_lhc/9298283

使用PULL解析器解析和生成XML文件:

Step 1 : 在项目的assets目录中放置一个XML文档books.xml,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<books>
    <book id="10001" ps="First">
        <name>Thinking In Java</name>
        <price>80.00</price>
    </book>
    <book id="10002" ps="Second">
        <name>Core Java</name>
        <price>90.00</price>
    </book>
    <book id="10003" ps="Third">
        <name>Hello, Andriod</name>
        <price>100.00</price>
    </book>
</books>

Step 2 : 创建一个List的对象,先来看一下Book.java的代码:

package com.lhc.xmlparser.bean;
public class Book {
    private int id;//编号
    private String ps;//名次
    private String name;//书名
    private float price;//价格
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getPs() {
        return ps;
    }
    public void setPs(String ps) {
        this.ps = ps;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "id:" + id  + ", ps:" + ps + ", name:" + name + ", price:" + price;
    }
}

Step 3 : 我们先为解析器定义一个BookParser接口,每种类型的解析器需要实现此接口。BookParser.java代码如下:

package com.lhc.xmlparser.parser;
import java.io.InputStream;
import java.util.List;
import com.lhc.xmlparser.bean.Book;
public interface BookParser {
    /**
     * 解析输入流 得到Book对象集合
     * @param is
     * @return
     * @throws Exception
     */
    public List<Book> parse(InputStream is) throws Exception;

    /**
     * 序列化Book对象集合 得到XML形式的字符串(用于生成新的xml文件)
     * @param books
     * @return
     * @throws Exception
     */
    public String serialize(List<Book> books) throws Exception;
}

Step 4 : 创建一个实现BookParser接口的解析器PullBookParser.java。

1.取得节点的值
//第一种方式
eventType = parser.next();
parser.getText();

//第二种方式
parser.nextText();
2.取得节点括号内属性的值
//第一种方式(获取属性"PS"的值)
parser.getAttributeValue(null,"ps");

//第二种方式(获取第index位置属性的值)
parser.getAttributeValue(index);

PullBookParser.java代码如下:

package com.lhc.xmlparser.parser;
import java.io.InputStream;
import java.util.List;
import com.lhc.xmlparser.bean.Book;
import java.io.StringWriter;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
public class PullBookParser implements BookParser {
    @Override
    public List<Book> parse(InputStream is) throws Exception {
        List<Book> books = null;
        Book book = null;
        XmlPullParser parser = Xml.newPullParser(); //由android.util.Xml创建一个XmlPullParser实例
        parser.setInput(is, "UTF-8");               //设置输入流 并指明编码方式
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
            case XmlPullParser.START_DOCUMENT://文档开头
                books = new ArrayList<Book>();
                break;
            case XmlPullParser.START_TAG://节点开头
                if (parser.getName().equals("book")) {
                    book = new Book();
                    int id = Integer.parseInt(parser.getAttributeValue(null,"id"));
                    //int id = Integer.parseInt(parser.getAttributeValue(0));
                    book.setId(id);
                    String ps = String.valueOf(parser.getAttributeValue(null,"ps"));
                    //String ps = String.valueOf(parser.getAttributeValue(1));
                    book.setPs(ps);
                } else if (parser.getName().equals("name")) {
                    eventType = parser.next();
                    book.setName(parser.getText());
                    //book.setName(parser.nextText());
                } else if (parser.getName().equals("price")) {
                    eventType = parser.next();
                    book.setPrice(Float.parseFloat(parser.getText()));
                    //book.setPrice(parser.nextText());
                }
                break;
            case XmlPullParser.END_TAG://节点结束
                if (parser.getName().equals("book")) {
                    books.add(book);
                    book = null;    
                }
                break;
            }
            eventType = parser.next();
        }
        return books;
    }

    @Override
    public String serialize(List<Book> books) throws Exception {
        XmlSerializer serializer = Xml.newSerializer(); //由android.util.Xml创建一个XmlSerializer实例
        StringWriter writer = new StringWriter();
        serializer.setOutput(writer);   //设置输出方向为writer
        serializer.startDocument("UTF-8", true);
        serializer.startTag("", "books");
        for (Book book : books) {
            serializer.startTag("", "book");
            serializer.attribute("", "id", book.getId() + "");
            serializer.startTag("", "name");
            serializer.text(book.getName());
            serializer.endTag("", "name");
            serializer.startTag("", "price");
            serializer.text(book.getPrice() + "");
            serializer.endTag("", "price");
            serializer.endTag("", "book");
        }
        serializer.endTag("", "books");
        serializer.endDocument();
        return writer.toString();
    }
}

Step 5 : 在MainActivity.java中完成调用。MainActivity.java代码如下:

package com.lhc.xmlparser;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import com.lhc.xmlparser.bean.Book;
import com.lhc.xmlparser.parser.BookParser;
import com.lhc.xmlparser.parser.PullBookParser;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
    private static final String TAG = "XML";
    private BookParser parser;
    private List<Book> books;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button readBtn = (Button) findViewById(R.id.btn_read);
        Button writeBtn = (Button) findViewById(R.id.btn_write);
        readBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    InputStream is = getAssets().open("books.xml");
                    parser = new PullBookParser();  //创建SaxBookParser实例
                    books = parser.parse(is);  //解析输入流
                    for (Book book : books) {
                        Log.i(TAG, book.toString());
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        });
        writeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String xml = parser.serialize(books);  //序列化

                    File sdCard = Environment.getExternalStorageDirectory();
                    sdCard = new File(sdCard, "/MyFiles");
                    sdCard.mkdirs();// 创建MyFiles目录(可创建多级目录)
                    sdCard = new File(sdCard, "books.xml");
                    FileOutputStream out = new FileOutputStream(sdCard);
                    Writer writer = new OutputStreamWriter(out);
                    try {
                        writer.write(xml);
                    } finally {
                        writer.close();
                    }

                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        });
    }
}

Step 6: 若要写入文件到SD卡中则需要在AndroidManifest.xml配置一下权限:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值