android解析xml (pull)
1. xml
<persons>
<person id="18">
<name>furong</name>
<age>20</age>
</person>
</persons>
2. 解析
public class PersonService {
//上下文
private Context context;
//生成构建方法
public PersonService(Context context) {
this.context = context;
}
// 把person.xml的输入流解析转化成List集合
public List<Person> getPersons(String filename) {
//资源文件
AssetManager manager = context.getAssets();
try {
InputStream iStream = manager.open(filename);
// android使用pull解析器
XmlPullParser parser = Xml.newPullParser();
// 设置解析器参数
parser.setInput(iStream, "utf-8");
// 获取解析器的事件类型
int type = parser.getEventType();
Person person = null;
List<Person> persons = new ArrayList<Person>();
while (type != XmlPullParser.END_DOCUMENT) {
if (type == XmlPullParser.START_TAG) {
if ("person".equals(parser.getName())) {
person = new Person();
int id = Integer.parseInt(parser.getAttributeValue(0));
person.setId(id);
} else if ("name".equals(parser.getName())) {
String name = parser.nextText();
person.setName(name);
} else if ("age".equals(parser.getName())) {
int age = parser.nextTag();
person.setAge(age);
}
}
if (type == XmlPullParser.END_TAG) {
if ("person".equals(parser.getName())) {
persons.add(person);
}
}
type = parser.next();
}
return persons;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "获取person.xml失败", Toast.LENGTH_SHORT).show();
return null;
}
}
}
XmlPullParser:该解析器是一个在org.xmlpull.v1中定义的解析功能的接口
读取到xml的声明返回 START_DOCUMENT; 结束返回 END_DOCUMENT ; 开始标签返回 START_TAG;结束标签返回 END_TAG; 文本返回 TEXT
3. 生成
public boolean savePerson(List<Person> persons) {
try {
//初始化XML序列化器
XmlSerializer serializer = Xml.newSerializer();
//在SD卡上创建文件,需要添加写外部存储设备的权限
File file = new File(Environment.getExternalStorageDirectory(), "person.xml");
FileOutputStream fileOutputStream = new FileOutputStream(file);
serializer.setOutput(fileOutputStream, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "persons");
for (Person person : persons) { //遍历集合
serializer.startTag(null, "person");
serializer.attribute(null, "id", person.getId() + ""); //加空白字符串转化成String
serializer.startTag(null, "name");
serializer.text(person.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(person.getAge() + "");
serializer.endTag(null, "age");
serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
//关闭流
fileOutputStream.flush();
fileOutputStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
XmlSerializer:它是一个接口,定义了XML信息集的序列