Android 產生和PULL解析xml

來源:互聯網
上載者:User

標籤:

一、單個對象產生xml

產生以下xml,該怎麼產生呢?

<?xml version=‘1.0‘ encoding=‘UTF-8‘ standalone=‘yes‘ ?><account>  <id>1</id>  <password>123456</password>  <name>傳說之美</name>  <createDate>2015-02-02 11:50:42</createDate></account>

先定義一個account類,屬性有id、name、password、createDate。

public class Account {    private String id;    private String password;    private String name;    private String createDate;    public Account() {        super();    }    public Account(String id, String password, String name, String createDate) {        super();        this.id = id;        this.password = password;        this.name = name;        this.createDate = createDate;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getCreateDate() {        return createDate;    }    public void setCreateDate(String createDate) {        this.createDate = createDate;    }    @Override    public String toString() {        return "Account [id=" + id + ", password=" + password + ", name=" + name + ", createDate=" + createDate + "]\n\n";    }}

定義好這個類,就可以利用XmlSerializer用於寫xml資料了。寫個方法,把產生的xml儲存在xmlparser_account.xml檔案。

/** * 單個對象產生xml * @param account */private static void XmlFileCreator(Account account) {File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/xmlparser_account.xml");try {if (!newxmlfile.exists())newxmlfile.createNewFile();} catch (IOException e) {Log.e("IOException", "exception in createNewFile() method");}FileOutputStream fileos = null;try {fileos = new FileOutputStream(newxmlfile);} catch (FileNotFoundException e) {Log.e("FileNotFoundException", "can‘t create FileOutputStream");}// XmlSerializer用於寫xml資料XmlSerializer serializer = Xml.newSerializer();try {// XmlSerializer 用 UTF-8 編碼serializer.setOutput(fileos, "UTF-8");serializer.startDocument(null, Boolean.valueOf(true));serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);serializer.startTag(null, "account");// xml-tree,由startTag開始,endTag結束serializer.startTag(null, "id");serializer.text(account.getId());serializer.endTag(null, "id");serializer.startTag(null, "password");serializer.text(account.getPassword());serializer.endTag(null, "password");serializer.startTag(null, "name");serializer.text(account.getName());serializer.endTag(null, "name");serializer.startTag(null, "createDate");serializer.text(account.getCreateDate());serializer.endTag(null, "createDate");serializer.endTag(null, "account");serializer.endDocument();// 寫xml資料到FileOutputStreamserializer.flush();// 關閉fileos,釋放資源fileos.close();} catch (Exception e) {Log.e("Exception", "error occurred while creating xml file");}}

產生account對象,單個對象產生xml

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");Account account = new Account("1", "123456", "傳說之美", sdf.format(new Date()));XmlFileCreator(account);

查看儲存的檔案

二、解析單個對象組成的xml為單個對象

把產生的xmlparser_account.xml檔案放在res/xml/下,將這個xml解析為Account對象。這裡用XmlResourceParser,XmlResourceParser繼承了xmlpullparse的類。

/** * 解析單個對象組成的xml和xml組 * @return */private List<Account> getListData() {List<Account> accountList = new ArrayList<Account>();XmlResourceParser xrp = getResources().getXml(R.xml.xmlparser_account);try {// 直到文檔的結尾處Account account = null;while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {String tagName = xrp.getName();if (xrp.getEventType() == XmlResourceParser.START_DOCUMENT){}// 如果遇到了開始標籤if (xrp.getEventType() == XmlResourceParser.START_TAG) {Log.i("", tagName);if(tagName.equals("account")){account = new Account();} else if (account != null) {if (tagName.equals("id")) {String id = xrp.nextText();// 通過屬性名稱來擷取屬性值account.setId(id);} else if (tagName.equals("password")) {String password = xrp.nextText();// 通過屬性索引來擷取屬性值account.setPassword(password);} else if (tagName.equals("name")) {String name = xrp.nextText();account.setName(name);} else if (tagName.equals("createDate")) {String createDate = xrp.nextText();account.setCreateDate(createDate);}}}if (xrp.getEventType() == XmlResourceParser.END_TAG) {if (tagName.equals("account") && account !=null) {accountList.add(account);account = null;}}xrp.next();// 擷取解析下一個事件}} catch (XmlPullParserException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return accountList;}

直接列印結果看看

Log.i("", getListData().toString());

log如下

 

三、單個對象組成的xml組

類似這樣

<?xml version=‘1.0‘ encoding=‘UTF-8‘ standalone=‘yes‘ ?><accounts>  <account>    <id>2</id>    <password>123456</password>    <name>傳說</name>    <createDate>2015-02-02 02:54:41</createDate>  </account>  <account>    <id>3</id>    <password>567890</password>    <name>之美</name>    <createDate>2015-02-02 02:54:41</createDate>  </account></accounts>

產生單個對象組 組成的xml組跟單個對象xml基本差不多,寫成了一個方法,把產生的xml儲存在xmlparser_accounts.xml檔案。

/** * 產生單個對象的xml數組 *  * @param data */private static void XmlFileCreator(List<Account> data) {File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/xmlparser_accounts.xml");try {if (!newxmlfile.exists())newxmlfile.createNewFile();} catch (IOException e) {Log.e("IOException", "exception in createNewFile() method");}FileOutputStream fileos = null;try {fileos = new FileOutputStream(newxmlfile);} catch (FileNotFoundException e) {Log.e("FileNotFoundException", "can‘t create FileOutputStream");}XmlSerializer serializer = Xml.newSerializer();try {serializer.setOutput(fileos, "UTF-8");serializer.startDocument(null, Boolean.valueOf(true));serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);serializer.startTag(null, "accounts");for (Account account : data) {serializer.startTag(null, "account");serializer.startTag(null, "id");serializer.text(account.getId());serializer.endTag(null, "id");serializer.startTag(null, "password");serializer.text(account.getPassword());serializer.endTag(null, "password");serializer.startTag(null, "name");serializer.text(account.getName());serializer.endTag(null, "name");serializer.startTag(null, "createDate");serializer.text(account.getCreateDate());serializer.endTag(null, "createDate");serializer.endTag(null, "account");}serializer.endTag(null, "accounts");serializer.endDocument();serializer.flush();fileos.close();} catch (Exception e) {Log.e("Exception", "error occurred while creating xml file");}}

簡單地用幾行代碼產生

Account account1 = new Account("2", "123456", "傳說", sdf.format(new Date()));Account account2 = new Account("3", "567890", "之美", sdf.format(new Date()));List<Account> accountList = new ArrayList<Account>();accountList.add(account1);accountList.add(account2);XmlFileCreator(accountList);

產生的檔案如下

四、解析單個對象組成的xml組

二、解析單個對象組成的xml為單個對象 一樣 ,請查看二

五、產生具有attribute的單個對象組成的xml組

類似如下,account裡面還包含一個attribute值如何產生,其實很簡單,在 三、單個對象組成的xml組 基礎上修改一點就可以了

<?xml version=‘1.0‘ encoding=‘UTF-8‘ standalone=‘yes‘ ?><accounts>  <account id="2">    <password>123456</password>    <name>傳說</name>    <createDate>2015-02-02 04:50:45</createDate>  </account>  <account id="3">    <password>567890</password>    <name>之美</name>    <createDate>2015-02-02 04:50:45</createDate>  </account></accounts>

修改地方為

for (Account account : data) {serializer.startTag(null, "account");serializer.attribute(null, "id", account.getId());//serializer.startTag(null, "id");//serializer.text(account.getId());//serializer.endTag(null, "id");serializer.startTag(null, "password");serializer.text(account.getPassword());serializer.endTag(null, "password");serializer.startTag(null, "name");serializer.text(account.getName());serializer.endTag(null, "name");serializer.startTag(null, "createDate");serializer.text(account.getCreateDate());serializer.endTag(null, "createDate");serializer.endTag(null, "account");}

六、解析具有attribute的單個對象組成的xml組

解析同理,跟四、解析單個對象組成的xml組 差不多,修改id部分解析即可

// 如果遇到了開始標籤if (xrp.getEventType() == XmlResourceParser.START_TAG) {Log.i("", tagName);if(tagName.equals("account")){account = new Account();String id = xrp.getAttributeValue(null, "id");account.setId(id);} else if (account != null) {if (tagName.equals("id")) {//String id = xrp.nextText();//account.setId(id);} else if (tagName.equals("password")) {String password = xrp.nextText();account.setPassword(password);} else if (tagName.equals("name")) {String name = xrp.nextText();account.setName(name);} else if (tagName.equals("createDate")) {String createDate = xrp.nextText();account.setCreateDate(createDate);}}}

本文原創連結:http://www.cnblogs.com/liqw/p/4267461.html

:http://download.csdn.net/detail/lqw770737185/8417583

Android 產生和PULL解析xml

聯繫我們

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