pull解析xml
public class PersonService {
private Context context;
public PersonService(Context context) {
this.context = context;
}
/**
* 把person.xml的输入流 解析 转化成list集合
* @param filename assets目录下的文件名
* @return
*/
public List<Person> getPersons(String filename){
AssetManager manager = context.getAssets();
try {
InputStream is = manager.open(filename);
//在android下使用pull解析xml文件
//1.获取pull解析器的实例
XmlPullParser parser = Xml.newPullParser();
//2.设置解析器的一些参数
parser.setInput(is, "utf-8");
// 获取pull解析器对应的事件类型
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 = Integer.parseInt( parser.nextText());
person.setAge(age);
}
}
if(type==XmlPullParser.END_TAG){
if("person".equals(parser.getName())){
persons.add(person);
person = null;
}
}
type = parser.next();
}
return persons;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "获取person.xml失败", Toast.LENGTH_SHORT).show();
return null;
}
}
/**
* 把persons集合里面的内容写到xml文件里面
* @param persons person的集合
* @return
*/
public boolean savePersonToXml(List<Person> persons){
try {
XmlSerializer serializer = Xml.newSerializer();
// /sdcard/person.xml
// mount unmount 文件系统的权限
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", person.getId()+"");
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();
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
pull解析
最新推荐文章于 2024-05-02 12:51:13 发布