android小功能實現之xml檔案解析(Pull)

來源:互聯網
上載者:User

標籤:xml解析   pull   

android解析XML常見的有三種Pull、SAX、Dom三種方式。
最常使用是Pull,Android工程本身解析XML也是用的Pull。
Pull是一個開源項目,其官方網站是:http://xmlpull.org/。
在Android工程中已經整合了Pull項目,可以直接使用。


建立一個Android工程。


一 添加測試檔案

在res目錄下建立一個raw檔案夾,在其中添加檔案persons.xml, 內容如下:

<?xml version="1.0" encoding="UTF-8"?><persons>    <person id ="1010">        <name>A</name>        <age>10</age>    </person>    <person id ="1111">        <name>B</name>        <age>11</age>    </person></persons>

二 布局
開啟main.xml修改內容如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <TextView android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:id="@+id/content" /></LinearLayout>

用於顯示從xml中解析出來的資料。


三 添加實體類
建立一個Person類,儲存讀出來的資料,類容如下:

public class Person {    private Integer id;    private String name;    private Integer age;    public void setId(Integer id) {        this.id = id;    }    public void setAge(Integer age) {        this.age = age;    }    public void setName(String name) {        this.name = name;    }    public Integer getId() {        return id;    }    public String getName() {        return name;    }    public Integer getAge() {        return age;    }    @Override    public String toString() {        return "Person{" +                "id=" + id +                ", name='" + name + '\'' +                ", age=" + age +                '}';    }}

四 功能實現
建立一個類PersonService,用於解析XML,完整代碼如下:

public class PersonService {    /**     * 擷取對象列表     *     * @param inStream xml檔案輸入資料流     * @return 對象列表     * @throws Exception     */    public List<Person> getPersons(InputStream inStream) throws Exception {        XmlPullParser parser = Xml.newPullParser();        try {            parser.setInput(inStream, "UTF-8");            int eventType = parser.getEventType();            Person currentPerson = null;            List<Person> persons = null;            while (eventType != XmlPullParser.END_DOCUMENT) {                switch (eventType) {                    case XmlPullParser.START_DOCUMENT:  // 文檔開始事件,可以進行資料初始化處理                        persons = new ArrayList<Person>();                        break;                    case XmlPullParser.START_TAG:       //開始讀取某個標籤                        //通過getName判斷讀到哪個標籤,然後通過nextText()擷取文本節點值,或通過getAttributeValue(i)擷取屬性節點值                        if (parser.getName().equalsIgnoreCase("person")) {                            currentPerson = new Person();                            currentPerson.setId(new Integer(parser.getAttributeValue(null, "id")));                        }                        else if (currentPerson != null) {                            String name = parser.getName();                            if (parser.getName().equalsIgnoreCase("name")) {                                currentPerson.setName(parser.nextText());// 如果後面是Text元素,即返回它的值                            } else if (name.equalsIgnoreCase("age")) {                                currentPerson.setAge(new Integer(parser.nextText()));                            }                        }                        break;                    case XmlPullParser.END_TAG:// 結束元素事件                        if (parser.getName().equalsIgnoreCase("person") && currentPerson != null) {                            persons.add(currentPerson);                            currentPerson = null;                        }                        break;                }                eventType = parser.next();            }            inStream.close();            return persons;        }        catch (Exception e) {            e.printStackTrace();        }        return null;    }}

五 測試代碼
修改MainActivity.java代碼如下:

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        try {            // 測試用:讀取檔案內容            // String str = "xml檔案內容:\n";            // str += this.read("person.xml");            InputStream xml = getResources().openRawResource(R.raw.persons);            String str = "xml檔案內容:\n";            PersonService service = new PersonService();            List<Person> persons = service.getPersons(xml);            for(Person person :persons) str = str + person.toString() + "\n";            xml.close();            TextView textView = (TextView)findViewById(R.id.content);            textView.setText(str);        }        catch (Exception e){            e.printStackTrace();        }    }    public String read(String name) throws  Exception{        InputStream is = getResources().openRawResource(R.raw.persons);        ByteArrayOutputStream os = new ByteArrayOutputStream();        byte[] buf = new byte[1024];        int len = 0;        while( (len = is.read(buf)) != -1){            os.write(buf,0, len);        }        byte[] data = os.toByteArray();        String content = new String(data);        return  content;    }

六 運行結果





android小功能實現之xml檔案解析(Pull)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.