android 自带 xml解析
引用:http://www.oschina.net/code/snippet_587413_13452
package service;
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;
import domin.Person;
public class PersonService {
/***
* 读取xml文件
* @param in 输入流
* @return person集合对象
* @throws Exception
*/
public static List<Person> Getpersons(InputStream in) throws Exception{
List<Person> persons = null;
Person person = null;
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(in, "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("name".equals(pullParser.getName())){
person.setName(pullParser.nextText());
}if("age".equals(pullParser.getName())){
person.setAge(new Integer(pullParser.nextText()));
}
break;
case XmlPullParser.END_DOCUMENT:
if("person".equals(pullParser.getName())){
persons.add(person);
person = null;
}
break;
}
event = pullParser.next();
}
return persons;
}
/***
* 保存xml文件
* @param persons 对象
* @param out 输出流
* @throws Exception
*/
public static void savePerson(List<Person> persons,OutputStream out) throws Exception{
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(out,"UTF-8");
serializer.startDocument("UTF-8", true);
serializer.startTag(null, "persons");
for(Person p:persons){
serializer.startTag(null, "person");
serializer.attribute(null, "id", p.getId().toString());
serializer.startTag(null, "name");
serializer.text(p.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(p.getAge()+"");
serializer.endTag(null, "age");
serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
out.flush();
out.close();
}
}
=============================
package domin;
public class Person {
private Integer id;
private String name;
private Integer age;
public Person() {
super();
}
public Person(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "id==="+id+"==姓名"+name+"==年龄"+age;
}
}