当前位置: 编程技术>移动开发
Android xml文件的序列化实现代码
来源: 互联网 发布时间:2014-10-23
本文导语: 传统方式: 代码如下:public void backSms(View view){ //假设我已经获取到了所有的短信 StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(""); for(SmsInfo info:smsInfos){ sb.append(""); sb.append(""); sb.append(info.getAddress()); ...
传统方式:
代码如下:
public void backSms(View view){
//假设我已经获取到了所有的短信
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append("");
for(SmsInfo info:smsInfos){
sb.append("");
sb.append("");
sb.append(info.getAddress());
sb.append("");
sb.append("");
sb.append(info.getType());
sb.append("");
sb.append("");
sb.append(info.getBody());
sb.append("");
sb.append("");
sb.append(info.getBody());
sb.append("");
sb.append("");
}
sb.append("");
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);
}
}