首先创建一个实例对象person,xml的格式如下:
<?xmlversion="1.0" encoding="UTF-8"?>
<persons>
<student id=“1">
<name>xiaoming</name>
<age>26</age>
</student>
<student id=“2">
<name>xiaoming</name>
<age>22</age>
</student>
</persons>
person:
public class person {
private int id;
private String nameString;
private int age;
利用source工具生成get set方法,tostring,构造方法。
xml读取保存工具类:
public void writexml(){
// 数据初始化
List<person> listpersonList = new ArrayList<person>();
for (int i = 0; i < 10; i++) {
person mPerson = new person(i, "xiaoming", i+20);
listpersonList.add(mPerson);
}
// 序列化开始
try {
XmlSerializer mxmlSerializer = Xml.newSerializer();
File mfile = new File(Environment.getExternalStorageDirectory(),"test.xml");
FileOutputStream mFileOutputStream= new FileOutputStream(mfile);
mxmlSerializer.setOutput(mFileOutputStream, "utf-8");
mxmlSerializer.startDocument("utf-8",true);
mxmlSerializer.startTag(null, "persons");
for(person mperson :listpersonList){
mxmlSerializer.startTag(null, "student");
mxmlSerializer.attribute(null, "id",String.valueOf(mperson.getId()));
// 写名字
mxmlSerializer.startTag(null, "name"); // <name>
mxmlSerializer.text(mperson.getNameString());
mxmlSerializer.endTag(null, "name"); // </name>
// 写年龄
mxmlSerializer.startTag(null, "age"); // <age>
mxmlSerializer.text(String.valueOf(mperson.getAge()));
mxmlSerializer.endTag(null, "age"); // </age>
mxmlSerializer.endTag(null, "student");
}
mxmlSerializer.endTag(null, "persons");
mxmlSerializer.endDocument();
System.out.println("write success!");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public List<person> readxml(){
List<person> personList = null;
try {
File path = new File(Environment.getExternalStorageDirectory(), "test.xml");
FileInputStream fis = new FileInputStream(path);
// 获得pull解析器对象
XmlPullParser parser = Xml.newPullParser();
// 指定解析的文件和编码格式
parser.setInput(fis, "utf-8");
int eventType = parser.getEventType(); // 获得事件类型
person person = null;
String id;
while(eventType != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName(); // 获得当前节点的名称
switch (eventType) {
case XmlPullParser.START_TAG: // 当前等于开始节点 <person>
if("persons".equals(tagName)) { // <persons>
personList = new ArrayList<person>();
} else if("student".equals(tagName)) { // <person id="1">
person = new person();
id = parser.getAttributeValue(null, "id");
person.setId(Integer.valueOf(id));
} else if("name".equals(tagName)) { // <name>
person.setNameString(parser.nextText());
} else if("age".equals(tagName)) { // <age>
person.setAge(Integer.parseInt(parser.nextText()));
}
break;
case XmlPullParser.END_TAG: // </persons>
if("student".equals(tagName)) {
// 需要把上面设置好值的person对象添加到集合中
personList.add(person);
}
break;
default:
break;
}
eventType = parser.next(); // 获得下一个事件类型
}
return personList;
} catch (Exception e) {
e.printStackTrace();
}
return personList;
}