Android中解析XML的方式主要有三種:sax,dom和pull關於其內容可參考:http://blog.csdn.net/liuhe688/article/details/6415593java
本文將主要介紹pull解析器解析xml文件,環境爲ubuntu 12.04+ intelij 13.1 + android sdk 2.1android
二.解析一個xml文件:git
assets/person.xmlgithub
<?xml version="1.0" encoding="UTF-8"?> <persons> <person id="1101"> <name>amos</name> <age>30</age> </person> <person id="1102"> <name>tom</name> <age>18</age> </person> </persons>
com/amos/xml/domain/Person.javaubuntu
package com.amos.xml.domain; /** * Created by amosli on 14-6-3. */ public class Person { private String name; private Integer age; private Integer id; public Integer getAge() { return age; } public void setAge(Integer age) { if (age < 1 || age > 100) { this.age = 0; } else { this.age = age; } } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
com/amos/xml/service/PersonService.javaapp
package com.amos.xml.service; import android.content.Context; import android.content.res.AssetManager; import android.util.Log; import android.util.Xml; import com.amos.xml.domain.Person; import org.xmlpull.v1.XmlPullParser; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Created by amosli on 14-6-3. */ public class PersonService { private Context context; public PersonService(Context context) { this.context = context; } /** * 把person.xml的輸入流解析轉化成list集合 * * @param * @return */ public List<Person> getPersons(String filename) { AssetManager manager = context.getAssets(); //初始化項目. List<Person> persons = null; Person person = null; try { InputStream inputStream = manager.open(filename); //在android下使用xmlpullparser進行解析 XmlPullParser xmlPullParser = Xml.newPullParser(); //設置xmlpullparser的一些參數 xmlPullParser.setInput(inputStream, "utf-8"); //獲取pull解析器對應事件類型 int eventType = xmlPullParser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: persons = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: if (xmlPullParser.getName().equals("person")) { person = new Person(); String id = xmlPullParser.getAttributeValue(0); Log.d("person.id", id); person.setId(Integer.parseInt(id)); eventType = xmlPullParser.next(); } else if (xmlPullParser.getName().equals("name")) { String name = xmlPullParser.nextText(); Log.d("person.name", name); person.setName(name); eventType = xmlPullParser.next(); } else if (xmlPullParser.getName().equals("age")) { String age = xmlPullParser.nextText(); Log.d("person.age", age); person.setAge(Integer.valueOf(age)); eventType = xmlPullParser.next(); } break; case XmlPullParser.END_TAG: if (xmlPullParser.getName().equals("person")) { persons.add(person); person = null; } break; } eventType = xmlPullParser.next(); } } catch (Exception e) { e.printStackTrace(); } return persons; } }
注:這裏解析主要用到的是eventType(事件類型),若是是START_DOCUMENT則表示讀到文檔開始位置,若是是START_TAG,則表示讀到文檔中的元素開始位置,如<name>,相似的結束位置爲END_DOCUMENT和END_TAG;其中要注意判斷其事件類型開始的名稱是什麼,而且取值時,注意其不一樣位置取值方式也不同,如<person id="1122">,那麼取id的方式爲getAttributeValue(int index),另外取<name >amos</name>,則要用nextText()方法進行取值.dom
/com/amos/xml/MyActivity.javaide
package com.amos.xml; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.amos.xml.domain.Person; import com.amos.xml.service.PersonService; import java.util.List; public class MyActivity extends Activity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView show_users = (TextView) findViewById(R.id.show_users); PersonService personService = new PersonService(this); StringBuilder stringBuilder = new StringBuilder(); List<Person> persons = personService.getPersons("person.xml"); for (Person person : persons) { stringBuilder.append(" " + person.getName()).append(":").append(person.getAge()); } System.out.println("stringBuilder:" + stringBuilder); show_users.setText(stringBuilder); Toast.makeText(this, "數據寫入成功!" + stringBuilder, Toast.LENGTH_LONG); } }
這裏我在主界面定義了一個TextView,用來顯示讀取到的xml文件的內容,效果以下圖所示:測試
首先,加入必要的配置:AndroidManifest.xmlui
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.amos.xml" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="7"/> <application android:label="@string/app_name"> <uses-library android:name="android.test.runner"/> <activity android:name="MyActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.amos.xml"/> </manifest>
其中加粗的部分是後加入到項目中的.
其次,寫一個testcase:/com/amos/xml/test/TestService.java
package com.amos.xml.test; import android.test.AndroidTestCase; import com.amos.xml.domain.Person; import com.amos.xml.service.PersonService; import java.util.List; /** * Created by amosli on 14-6-3. */ public class TestService extends AndroidTestCase { public void testGetPersons() throws Exception { PersonService personService = new PersonService(getContext()); List<Person> persons = personService.getPersons("person.xml"); for (Person person : persons) { System.out.println(person.getName()); } } }
這裏想要查看每一步的運行步驟,能夠加上斷點,intelij 中的快捷鍵是F8(step over),F7(step into),F9(Resume program).