Android提供了XmlSerializer来实现XML文件的序列化。相比传统方式,更高效安全。
传统方式:
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); } }