android中通过pull解释器解析xml
2012-11-06 16:24:20 来源:WEB开发网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
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);
}
if("age".equals(pullParser.getName())){
int age = Integer.parseInt(pullParser.nextText());
person.setAge(age);
}
break;
case XmlPullParser.END_TAG://如果解释标签是perosn就将person对象存放到list中
if("person".equals(pullParser.getName())){
persons.add(person);
}
break;
case XmlPullParser.END_DOCUMENT:
break;
default:
break;
}
//pull不会主动向后执行,所以自己调用next方法并把值付给event
event = pullParser.next();
}
System.out.println("persons.size()-->"+persons.size());
return persons;
}
}
6、Person.java
public class Person {
private Integer id;
private String name;
private Integer 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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
更多精彩
赞助商链接