Android入門:Pull解析XML

來源:互聯網
上載者:User
文章目錄
  • 應用:建立上面提到的person.xml檔案到/data/data/package/files中
一、Pull解析器介紹

pull解析類似於SAX\DOM,都是用來解析XML的方法;

二、使用Pull解析器讀取XML資料

模板代碼如下:

XmlPullParser parser = Xml.newPullParser();   //建立一個PULL解析器parser.setInput(in,"UTF-8");      //讀取的編碼為UTF-8int event = parser.getEventType();   //開始解析時調用while(event!=XmlPullParser.END_DOCUMENT){//parser.getName();   //獲得當前指向的標籤的標籤名//parser.getAttributeValue(0);  //獲得當前指向的標籤的第1個屬性值//parser.nextText(); //獲得當前標籤的標籤值switch(event){case XmlPullParser.START_DOCUMENT: //如果指向的是START_DOCUMENT//處理break;case XmlPullParser.START_TAG:    //如果指向的是START_TAG//處理break;case XmlPullParser.END_TAG:     //如果指向的是END_TAG//處理break;}event = parser.next();     //指向下一個標籤}

應用:讀取/data/data/package/files/目錄下的person.xml檔案

XML檔案如下:

<?xml version="1.0" encoding="UTF-8"?><persons>    <person id="1">        <name>xiazdong-1</name>        <age>20</age>    </person>    <person id="2">        <name>xiazdong-2</name>        <age>30</age>    </person></persons>

從上面可以看出,<person></person>可以看做一個JavaBean,而<persons></persons>組成了一個person隊列;

因此我們建立一個Person的JavaBean:

package org.xiazdong.vo;public class Person {private int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Person(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}public Person() {}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";}}

接下來,我們編寫如下readXML方法,使得將XML檔案中的資料變成一個person隊列;

public class XmlService {public List<Person> readXml(InputStream in) throws Exception {XmlPullParser parser = Xml.newPullParser();parser.setInput(in, "UTF-8");List<Person> list = null;Person person = null;int event = parser.getEventType();  //開始解析,並擷取事件/* * 可選事件包括: * (1)START_DOCUMENT * (2)END_DOCUMENT * (3)START_TAG * (4)END_TAG * */while (event != XmlPullParser.END_DOCUMENT) {switch (event) {case XmlPullParser.START_DOCUMENT:list = new ArrayList<Person>();break;case XmlPullParser.START_TAG:if ("person".equals(parser.getName())) {person = new Person();int id = Integer.parseInt(parser.getAttributeValue(0));person.setId(id);}if("name".equals(parser.getName())){person.setName(parser.nextText());}if("age".equals(parser.getName())){person.setAge(Integer.parseInt(parser.nextText()));}break;case XmlPullParser.END_TAG:if("person".equals(parser.getName()))list.add(person);break;}event = parser.next();  //讀取下一個}return list;}}

編寫好此方法之後,我們可以測試此方法:

public class XmlTest extends AndroidTestCase{private static final String TAG = "XmlTest";public void testRead() throws Exception{XmlService service = new XmlService();List<Person> list = service.readXml(this.getContext().openFileInput("person.xml"));Log.i(TAG, String.valueOf(list.size()));for(Person p:list){Log.i(TAG, p.toString());}}}

運行效果如下:

三、使用Serializer解析器寫入XML檔案

核心代碼如下:

XmlSerializer serializer = Xml.newSerializer();    //建立一個Serializer解析器serializer.setOutput(out,"utf-8");      //設定輸出資料流及輸出的編碼為UTF-8serializer.startDocument("UTF-8",true);   //輸出開始文檔<?xml version="1.0" encoding="UTF-8" standalone="true"?>serializer.startTag(null,"tagname");   //輸出<tagname>serializer.attribute(null,"name","value");  //輸出<tagname name="value">serializer.text("value");    //輸出<tagname></tagname>serializer.endTag(null,"tagname");//結束標籤serializer.endDocument();//結束文檔

應用:建立上面提到的person.xml檔案到/data/data/package/files中以下代碼用於將person隊列寫入輸出資料流檔案(此處為檔案輸出資料流)

public class XmlService {public void writeXml(List<Person> list,OutputStream out)throws Exception{XmlSerializer serializer = Xml.newSerializer();serializer.setOutput(out, "UTF-8");serializer.startDocument("UTF-8", true);serializer.startTag(null, "persons");for(Person p:list){serializer.startTag(null,"person");serializer.attribute(null, "id", String.valueOf(p.getId()));serializer.startTag(null, "name");serializer.text(p.getName());serializer.endTag(null, "name");serializer.startTag(null, "age");serializer.text(p.getAge()+"");serializer.endTag(null, "age");serializer.endTag(null, "person");}serializer.endTag(null, "persons");serializer.endDocument();out.flush();out.close();}}

測試代碼如下:

public class XmlTest extends AndroidTestCase{public void testWrite()throws Exception{XmlService service = new XmlService();List<Person> list = new ArrayList<Person>();for(int i=0;i<3;i++){Person p = new Person();p.setId(i);p.setName("xiazdong-"+i);p.setAge(20+i);list.add(p);}OutputStream out = this.getContext().openFileOutput("person.xml", Context.MODE_PRIVATE);service.writeXml(list, out);}}

總結:使用Pull解析器讀取,使用Serializer寫入;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.