Android xml文件的序列化实现代码
程序员文章站
2022-06-19 19:50:08
传统方式:
复制代码 代码如下:public void backsms(view view){ //假设我已经获取到了所有的短信 &nbs...
传统方式:
复制代码 代码如下:
public void backsms(view view){
//假设我已经获取到了所有的短信
stringbuilder sb = new stringbuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<smss>");
for(smsinfo info:smsinfos){
sb.append("<sms>");
sb.append("<address>");
sb.append(info.getaddress());
sb.append("</address>");
sb.append("<type>");
sb.append(info.gettype());
sb.append("</type>");
sb.append("<body>");
sb.append(info.getbody());
sb.append("</body>");
sb.append("<date>");
sb.append(info.getbody());
sb.append("</date>");
sb.append("</sms>");
}
sb.append("</smss>");
try{
file file = new file(environment.getexternalstoragedirectory(),"backup.xml");
fileoutputstream fos = new fileoutputstream(file);
fos.write(sb.tostring().getbytes());
toast.maketext(this, "备份成功", toast.length_long).show();
}catch(exception e){
e.printstacktrace();
toast.maketext(this, "备份失败", toast.length_long).show();
}
}
采用xmlserializer实现的方式:
复制代码 代码如下:
public void backsms2(view view){
try{
xmlserializer serializer = xml.newserializer();
file file = new file(environment.getexternalstoragedirectory(),"backup2.xml");
fileoutputstream os = new fileoutputstream(file);
//初始化序列号器 指定xml数据写入到哪个文件 并且指定文件的编码方式
serializer.setoutput(os,"utf-8");
serializer.startdocument("uft-8", true);
serializer.starttag(null, "smss");
for(smsinfo info:smsinfos){
serializer.starttag(null, "sms");
serializer.attribute(null, "id", info.getid()+"");
serializer.starttag(null, "body");
serializer.text(info.getbody());
serializer.endtag(null, "body");
serializer.starttag(null, "address");
serializer.text(info.getaddress());
serializer.endtag(null, "address");
serializer.endtag(null, "sms");
}
serializer.endtag(null, "smss");
serializer.enddocument();
}catch(exception e){
e.printstacktrace();
toast.maketext(this, "备份失败", 0);
}
}
上一篇: android异步任务设计思详解(AsyncTask)
下一篇: 手写android布局示例