解析Xml
public class ParserUtils {
public static List<Person> parserXml(InputStream open) {
ArrayList<Person> list=null;
Person person=null;
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(open, "utf-8");
int type = parser.getEventType();
while(type!=XmlPullParser.END_DOCUMENT){
String name=parser.getName();
switch (type) {
case XmlPullParser.START_TAG:
if("persons".equals(name)){
list=new ArrayList<Person>();
}else if("person".equals(name)){
person=new Person();
}else if("name".equals(name)){
person.setName(parser.nextText());
person.setPic(parser.getAttributeValue(0));
}else if("age".equals(name)){
person.setAge(Integer.parseInt(parser.nextText()));
}break;
case XmlPullParser.END_TAG:
if("person".equals(name)){
list.add(person);
System.out.println(person);
person=null;
}
break;
}
type=parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
创建Xml文件
XmlSerializer serializer = Xml.newSerializer();
try {
File file=new File(Environment.getExternalStorageDirectory(),"persons.xml");
FileOutputStream os=new FileOutputStream(file);
serializer.setOutput(os, "utf_8");
serializer.startDocument("utf_8", true);
serializer.startTag(null, "persons");
for (Person p : list) {
serializer.startTag(null, "person");
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();
} catch (Exception e) {
e.printStackTrace();
}