android xml解析-Pull解析

时间:2022-10-31 13:07:55

解析一下的xml为例:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>daidai</name>
<age>20</age>
</person>
<person id="20">
<name>wxxu</name>
<age>25</age>
</person>
</persons>
1.调用解析方法

public void testPersons() throws Exception{
InputStream xml = this.getClass().getClassLoader().getResourceAsStream("person.xml");
List<Person> persons = PersonService.getPersons(xml);
for(Person person : persons){
Log.i(TAG, person.toString());
}
}
2.PersonService中的getPersons(xml)方法

public static List<Person> getPersons(InputStream xml) throws Exception{
List<Person> persons = null;
Person person = null;
XmlPullParser pullParser = Xml.newPullParser();
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 = new Integer(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 = new Integer(pullParser.nextText());
person.setAge(age);
}
break;

case XmlPullParser.END_TAG:
if("person".equals(pullParser.getName())){
persons.add(person);
person = null;
}
break;
}
event = pullParser.next();
}
return persons;
}
3.生成xml方法的调用

public void testSave() throws Exception{
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(43, "zhangxx", 80));
persons.add(new Person(12, "lili", 20));
persons.add(new Person(78, "xiaoxiao", 8));
File xmlFile = new File(getContext().getFilesDir(), "itcast.xml");
FileOutputStream outStream = new FileOutputStream(xmlFile);
PersonService.save(persons, outStream);
}
4.PersonService中的save保存成xml方法

public static void save(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 person : persons){
serializer.startTag(null, "person");
serializer.attribute(null, "id", person.getId().toString());

serializer.startTag(null, "name");
serializer.text(person.getName());
serializer.endTag(null, "name");

serializer.startTag(null, "age");
serializer.text(person.getAge().toString());
serializer.endTag(null, "age");

serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
out.flush();
out.close();
}