public class Student {
private String id;
private String name;
private int age;
private String sex;
public String getId() {
return id;
}
public void setId(String 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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
package com.example.xmlparserofpull;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;
public class ParserByPULL {
public static List<Student> getStudents(InputStream inStream) throws Throwable
{
List<Student> students = null;
Student mStudent = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inStream, "UTF-8");
int eventType = parser.getEventType();
while(eventType!=XmlPullParser.END_DOCUMENT)
{ switch (eventType)
{ case XmlPullParser.START_DOCUMENT:
students = new ArrayList<Student>();
break;
case XmlPullParser.START_TAG:
String name = parser.getName();
if("student".equals(name))
{
mStudent = new Student();
mStudent.setId(parser.getAttributeValue(0));
}
if(mStudent!=null)
{
if("name".equals(name))
{
mStudent.setName(parser.nextText());
}
if("age".equals(name))
{
mStudent.setAge(new Short(parser.nextText()));
}
if("sex".equals(name))
{
mStudent.setSex(parser.nextText());
}
}
break;
//触发结束元素事件
case XmlPullParser.END_TAG:
if("student".equals(parser.getName()))
{
students.add(mStudent);
mStudent = null;
}
break;
default:
break;
}
eventType = parser.next();
}
return students;
}
}
package com.example.xmlparserofpull;
import java.io.InputStream;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager asset = getAssets();
try {
InputStream input = asset.open("student.xml");
List<Student> list = ParserByPULL.getStudents(input);
for (Student stu : list) {
Log.e("StudentInfo","Person ID: " + stu.getId() + ","
+ stu.getName() + ", " + stu.getAge() + ", "
+ stu.getSex());
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}