Pull解析

第一步,在res目录下新建一个raw文件夹,然后new一个.xml文件如 tt.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
  <person id="24">
     <name>LiSi</name>
<age>22</age>
</person> 
  <person id="29">
     <name>ShanJi</name>
<age>26</age>
</person> 
</persons>

第二步,在src下新建一个实体类Person 内容如下:

public class Person {
private Integer id;
private String name;
private Short 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;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}

第三步新建一个用来解析XML的类如PullPersonService内容如下:

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
public class PullPersonService {
public static List<Person> getPersons(InputStream inStream) throws Exception{
Person person = null;
List<Person> persons=null;
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(inStream,"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 = new Integer(pullParser.getAttributeValue(0));
person = new Person();
person.setId(id);
}
if(person!=null){
if("name".equals(pullParser.getName())){
person.setName(pullParser.nextText());
}
if("age".equals(pullParser.getName())){
person.setAge(new Short(pullParser.nextText()));
}
}
break;
case  XmlPullParser.END_TAG:
if("person".equals(pullParser.getName())){
persons.add(person);
person=null;
}
break;
}
event=pullParser.next();
}
return persons;
}

}

第四步在MainActivity中回调PullPersonService类中的方法。

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
getPersons();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    public void getPersons() throws Exception{
    InputStream is = getResources().openRawResource(R.raw.tt);
    List<Person> list = PullPersonService.getPersons(is);
    for(Person persons:list){
    Log.d("TAG","pull--list=="+persons.toString());
    }
    }    

}

你可能感兴趣的:(Pull解析)