Android Pull 读取XML
package com.wentian.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
import com.wentian.bean.Person;
public class XmlService {
public static List<Person> read(File file){
List<Person> persons = null;
Person p = null;
try {
FileInputStream inputStream = new FileInputStream(file);
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inputStream, "utf-8");
int type = parser.getEventType();
while(type != XmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_DOCUMENT:
persons = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
String name = parser.getName();
if(name.equals("person")){
p = new Person();
p.setId(Integer.parseInt(parser.getAttributeValue(0)));
}
else if(name.equals("name")){
p.setName(parser.nextText());
}
else if(name.equals("age")){
p.setAge(Short.parseShort(parser.nextText()));
}
break;
case XmlPullParser.END_TAG:
if(parser.getName().equals("person")){
persons.add(p);
p = null;
}
break;
/*case XmlPullParser.END_DOCUMENT:
inputStream.close();
return persons;*/
}
type = parser.next();
}
inputStream.close();
return persons;
}
catch (Exception e) {
//Log.e("XmlService", e.toString());
}
return null;
}
public static boolean write(List<Person> persons,File file) {
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(new FileWriter(file));
serializer.startDocument("UTF-8", true);
//第一个参数为命名空间,如果不使用命名空间,可以设置为null
serializer.startTag("", "persons");
for (Person person : persons){
serializer.startTag("", "person");
serializer.attribute("", "id", String.valueOf(person.getId()));
serializer.startTag("", "name");
serializer.text(person.getName());
serializer.endTag("", "name");
serializer.startTag("", "age");
serializer.text(String.valueOf(person.getAge()));
serializer.endTag("", "age");
serializer.endTag("", "person");
}
serializer.endTag("", "persons");
serializer.endDocument();
//return writer.toString();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}