應用情境
在Android應用開發過程中,有時候我們自己有一些XML檔案是我們自己手動建立的,而在項目開發過程中可能會用到,也就是說這用到了原始的XML資源檔。這個XML原始資源檔我們可以通過Resouce類的以下兩個方法來獲得:
getResouce.getXml(int id);
getRawResouce(int id)
這兩個方法返回的對象是一個XmlResouceParser類的對象。而XmlResouceParser類是XmlPullParser類的子類,所以我們可以Android內建的Pull模式解析我們的XML檔案,這也是本人比較喜歡的一種解析XML檔案方式。因為它相對於DOM解析具有佔有記憶體小,解析快,相對於SAX來說編寫代碼不那麼複雜,只要編寫那麼一點代碼就可以完成對XML檔案的解析。
關於PULL模式解析XML檔案,可以參看我之前寫的一篇文章:
Android平台下的XML檔案解析之PULL模式解析 .
http://blog.csdn.net/jiahui524/article/details/6955196
執行個體 :使用原始XML檔案
實現效果:
實現過程:
1、在res/下建立一個xml的檔案夾,在這個檔案夾下建立一個person.xml檔案,內容如下
<?xml version="1.0" encoding="UTF-8"?><persons><person id="1"><name>張三</name><age>20</age></person><person id="2"><name>李四</name><age>22</age></person></persons>
2、編寫布局檔案:main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btnParser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="解析原始XML資源檔" /> <EditText android:id="@+id/edtContent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:lines="5" /></LinearLayout>
3、編寫Activity的代碼
package com.jiahui.xmlres;import android.app.Activity;import android.content.res.XmlResourceParser;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;public class XmlResTestActivity extends Activity {private Button btnParser;private EditText edtContent;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);btnParser = (Button) this.findViewById(R.id.btnParser);edtContent = (EditText) this.findViewById(R.id.edtContent);btnParser.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// 擷取res/xml下的原生XML檔案XmlResourceParser parser = getResources().getXml(R.xml.persons);try {StringBuilder sb = new StringBuilder();int eventType = parser.getEventType();while (eventType != XmlResourceParser.END_DOCUMENT) {switch (eventType) {case XmlResourceParser.START_TAG:String tagName = parser.getName();if (("person").equals(tagName)) {// 得到第一個屬性String personid = parser.getAttributeValue(0);sb.append("ID:" + personid);} else if ("name".equals(parser.getName())) {String name = parser.nextText();sb.append("姓名:" + name);} else if ("age".equals(parser.getName())) {String age = parser.nextText();sb.append("年齡:" + age);}break;case XmlResourceParser.END_TAG:// 結束時加一個空行if ("person".equals(parser.getName())) {sb.append("\n");}break;default:break;}// 解析下一個事件eventType = parser.next();}// 將解析的結果放在文本編輯框edtContent.setText(sb.toString());} catch (Exception e) {// TODO: handle exception}}});}}
如需轉載引用請註明出處:http://blog.csdn.net/jiahui524