android中通过pull解释器解析xml
android中已经集成了pull解释器,所以不用添加jar文件,如果在javaee中使用pull需要手动添加pull的jar文件。android系统本身就是通过pull解释器来处理xml文件。所以说明pull还是有一定的优越性。
1、main.xml
[html]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
2、item.xml
[html]
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent" www.zzzyk.com
android:layout_height="wrap_content" />
3、我将person.xml文件放到了android的assets文件夹下
[html]
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>jack</name>
<age>16</age>
</person>
<person id="24">
<name>tom</name>
<age>15</age>
</person>
</persons>
4、MainActivity.java
[java]
public class MainActivity extends Activity {
private PersonService ps = null;
private ListView lv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ps = new PersonService();
lv = (ListView) this.findViewById(R.id.lv);
try {
AssetManager am = getAssets();
InputStream is = am.open("person.xml");
List<Person> list = ps.getPersons(is);
List<String> names = new ArrayList<String>();
for(Person p:list){
String name = p.getName();
names.add(name);
System.out.println(name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item, 0,names);
lv.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5、PersonService.java
[java]
public class PersonService {
public List<Person> getPersons(InputStream xml) throws Exception{
XmlPullParser pullParser = Xml.newPullParser();
List<Person> persons = null;
Person person = null;
pullParser.setInput(xml, "utf-8");
int event = pullParser.getEventType();
//判断是否解释到文档结束部分
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_DOCUMENT:
persons = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
if("person".equals(pullParser.getName())){
//得到标签中的第一个参数的值
int id = Integer.parseInt(pullParser.getAttributeValue(0));
person = new Person();
person.setId(id);
}
if("name".equals(pullParser.getName())){
//得到标签中间的文本内容
String name = pullParser.nextText();
person.setName(name);
}
补充:移动开发 , Android ,