序列化和xmlPull解析

发表于:,更新于:,By Sally
大纲
  1. 1. xml文件示例
  2. 2. 将xml文件写到本地
    1. 2.1. 首先,需要一个对象,如上xml文件所示,这里需要一个person对象
    2. 2.2. 准备一点假数据🏠🌲
    3. 2.3. 开始写
  3. 3. pull解析xml文件

xml文件示例

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8" standalone="true"?>
<persons>
<person id="0">
<name>zhangsan</name>
<age>20</age>
</person>
</persons>

将xml文件写到本地

首先,需要一个对象,如上xml文件所示,这里需要一个person对象

1
2
3
4
5
6
public class Person {
private int id;
private String name;
private int age;
// 构造方法,get,set,toString方法等等...
}

准备一点假数据🏠🌲

1
2
3
4
List<Person> persons = new ArrayList<Person>();
for(int i=0; i<20; i++) {
persons.add(new Person(i, ("zhangsan" + i), (10 + i)));
}

开始写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 获得序列化对象
XmlSerializer serializer = Xml.newSerializer();
try {
// 写到sd卡的person.xml文件中
File file = new File(Environment.getExternalStorageDirectory(), "person.xml");
FileOutputStream fos = new FileOutputStream(file);

serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "persons");
for(Person person : persons) {
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();
}

pull解析xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
try {
File file = new File(Environment.getExternalStorageDirectory(), "person.xml");
FileInputStream fis = new FileInputStream(file);

XmlPullParser parse = Xml.newPullParse();
parse.setInput(fis, "utf-8");

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

int eventType = parse.getEventType();
while(eventType != XmlPullParser.END_DOEUMENT) {
String tagName = parse.getName();
switch(eventType) {
case XmlPullParser.START_TAG:
if("persons".equals(tagName)) {
persons = new ArrayList<Person>();
} else if("person".equals(tagName)) {
person = new Person();
person.setId(Integer.valueOf(parse.getAttributeValue(null, "id")));
} else if("name".equals(tagName)) {
person.setName(parse.nextText());
} else if("age".equals(tagName)) {
person.setAge(Integer.valueOf(parse.nextText()));
}
break;
case XmlPullParser.END_TAG:
if("person".equals(tagName)) {
persons.add(person);
}
break;
}
eventType = parse.next();
}
return persons;
} catch(Exception e) {
e.printStackTrace();
}