xml的序列化
第一种方法 Stringbuffer
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"encoding=\"utf-8\"?>");
sb.append("<persons>");
for (int i = 0; i <persons.size(); i++) {
sb.append("<person>");
sb.append("<name>");
sb.append(persons.get(i).getName());
sb.append("</name>");
sb.append("<age>");
sb.append(persons.get(i).getAge());
sb.append("</age>");
sb.append("</person>");
}
sb.append("</persons>");
String xml =sb.toString();
try {
FileOutputStream fos = openFileOutput("person.xml",MODE_PRIVATE);
fos.write(xml.getBytes());
fos.close();
第二种方法:Xmlserlizer
public void create(View v){
try {
List<PersonInfo>infos = new ArrayList<PersonInfo>();
infos.add(newPersonInfo(1, "冠希哥", 32));
infos.add(newPersonInfo(2, "霆锋", 32));
//把对象集合变成xml
//xml序列化器
XmlSerializer serializer = Xml.newSerializer();//使用接口去接收一个真实的对象
FileOutputStream os = openFileOutput("persons.xml",Context.MODE_PRIVATE);
serializer.setOutput(os,"utf-8");//指定数据输出的路径
serializer.startDocument("utf-8",true);//文档的开始
serializer.startTag(null,"persons");//标签的开始
for(PersonInfo info:infos){
serializer.startTag(null,"person");
serializer.attribute(null,"id", info.id+"");//属性
//name
serializer.startTag(null,"name");
serializer.text(info.name);//文本节点
serializer.endTag(null,"name");
//age
serializer.startTag(null,"age");
serializer.text(info.age+"");
serializer.endTag(null,"age");
serializer.endTag(null,"person");
}
serializer.endTag(null, "persons");//标签的结束
serializer.endDocument();//文档的结束
os.close();//关流
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
xml文件反序列化
publicvoid parse(View v){
List<PersonInfo> infos = null;
PersonInfo info = null;
try {
//获取解析器
XmlPullParser parser = Xml.newPullParser();
FileInputStreaminputStream = openFileInput("persons.xml");
parser.setInput(inputStream,"utf-8");//把流设置给解析器
inteventType = parser.getEventType();//获取事件类型
while(eventType!= XmlPullParser.END_DOCUMENT){//判断是否解析到了文档的结尾
switch (eventType) {
case XmlPullParser.START_TAG://标签的开始
if("persons".equals(parser.getName())){//获取当前标签的名称
infos = newArrayList<PersonInfo>();
}elseif("person".equals(parser.getName())){
info = new PersonInfo();
int id = Integer.parseInt(parser.getAttributeValue(0));//获取属性
info.id = id;
}elseif("name".equals(parser.getName())){
String name = parser.nextText();//获取下一个文本节点的值
info.name = name;
}elseif("age".equals(parser.getName())){
int age =Integer.parseInt(parser.nextText());
info.age = age;
}
break;
case XmlPullParser.END_TAG://标签的结束
if("person".equals(parser.getName())){
infos.add(info);
info = null;
}
break;
default:
break;
}
//继续往下解析
eventType = parser.next();
}
//打印日志
for(PersonInfopersonInfo:infos){
Log.i(TAG, personInfo.toString());
}
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}