读写Xml文件

写Xml文件:

XmlSerializer serializer = Xml.newSerializer();
File path = new File(Environment.getExternalStorageDirectory(),"persons.xml");

FileOutputStream fos;
try {
fos = new FileOutputStream(path);
serializer.setOutput(fos, "utf-8");

serializer.startDocument("utf-8", true);

serializer.startTag(null, "persons");

serializer.startTag(null, "person");
serializer.attribute(null, "id", "18");

serializer.startTag(null, "name");
serializer.text("zs");
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text("28");
serializer.endTag(null, "age");

serializer.endTag(null, "person");

serializer.endTag(null, "persons");
serializer.endDocument();


读Xml文件:

XmlPullParser parser = Xml.newPullParser();

try {
FileInputStream fis = new FileInputStream(path);

parser.setInput(fis, "utf-8");

int eventType = parser.getEventType();

List<Person> list = null;
Person person = null;

while(eventType!=parser.END_DOCUMENT){

switch(eventType){
case XmlPullParser.START_TAG:
if(parser.getName().equals("persons")){
list = new ArrayList<Person>();
}else if(parser.getName().equals("person"))
{
person = new Person();
}else if(parser.getName().equals("name"))
{
person.setName(parser.nextText());
}else if(parser.getName().equals("email"))
{
person.setEmail(parser.nextText());
}else if(parser.getName().equals("address"))
{
person.setAddress(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if(parser.getName().equals("person")){
list.add(person);

person = null;
}
break;

default:
break;
}

eventType = parser.next();
}


你可能感兴趣的:(读写Xml文件)