Android xml file serialization implementation code

  • 2020-05-26 10:05:52
  • OfStack

Traditional ways:


public void backSms(View view){
  // Let's say I've got all the text messages 
  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, " The backup successful ", Toast.LENGTH_LONG).show();
  }catch(Exception e){
   e.printStackTrace();
   Toast.makeText(this, " Backup failure ", Toast.LENGTH_LONG).show();
  }

 }

The implementation method of XmlSerializer is adopted:


public void backSms2(View view){
  try{
   XmlSerializer serializer =  Xml.newSerializer();
   File file = new File(Environment.getExternalStorageDirectory(),"backup2.xml");
   FileOutputStream os = new FileOutputStream(file);
   // Initializes the sequence number   The specified XML To which file the data is written   And specify how the file is encoded 
   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, " Backup failure ", 0);
  }

 }


Related articles: