XML文件是一种常用的文件格式,可以用来存储与传递数据 ,本文是XML文件序列化与解析的一个简单示例
写文件到本地,并用XML格式存储
/**
* 写xml文件到本地
*/
private void writeXmlToLocal() {
List<Person> personList = getPersonList();
XmlSerializer serializer = Xml.newSerializer();
try {
File path = new File(Environment.getExternalStorageDirectory(), "persons.xml");
FileOutputStream fos = new FileOutputStream(path);
serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "persons");
for (Person person : personList) {
serializer.startTag(null, "person");
serializer.attribute(null, "id", String.valueOf(person.getId()));
serializer.startTag(null, "name");
serializer.text(person.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(String.valueOf(person.getAge()));
serializer.endTag(null, "age");
serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
} catch (Exception e) {
e.printStackTrace();
}
}
private List<Person> getPersonList() {
List<Person> personList = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
personList.add(new Person(i, "wang" + i, 18 + i));
}
return personList;
}
XML解析实现
private List<Person> parserXmlFromLocal() {
try {
File path = new File(Environment.getExternalStorageDirectory(), "persons.xml");
FileInputStream fis = new FileInputStream(path);
XmlPullParser parser = Xml.newPullParser();
parser.setInput(fis, "utf-8");
int eventType = parser.getEventType();
List<Person> personList = null;
Person person = null;
String id;
while(eventType != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if("persons".equals(tagName)) {
personList = new ArrayList<Person>();
} else if("person".equals(tagName)) {
person = new Person();
id = parser.getAttributeValue(null, "id");
person.setId(Integer.valueOf(id));
} else if("name".equals(tagName)) {
person.setName(parser.nextText());
} else if("age".equals(tagName)) {
person.setAge(Integer.parseInt(parser.nextText()));
}
break;
case XmlPullParser.END_TAG:
if("person".equals(tagName)) {
personList.add(person);
}
break;
default:
break;
}
eventType = parser.next();
}
return personList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
测试结果
public class TestCase extends AndroidTestCase {
public void test() {
List<Person> personList = parserXmlFromLocal();
for (Person person : personList) {
Log.i("TestCase", person.toString());
}
}
完成