生成XML——XmlSerializer

    public void backup (View view){
        try {
            //写入外存记得要添加权限
             // 
             // 
            File file = new File(Environment.getExternalStorageDirectory(), "back.xml");
            FileOutputStream fos = new FileOutputStream(file);
            //获取序列化器 用于生成XML文件
            XmlSerializer serializer = Xml.newSerializer();
            //设置输出流编码格式
            serializer.setOutput(fos, "UTF-8");

            //xml文件头部:
            serializer.startDocument("UTF-8", true);//true表示standalone='yes'

            //根标签:开始
            serializer.startTag(null, "smss");
            for(Sms sms:smss){
                //对于每一个短信设置根标签
                serializer.startTag(null, "sms");
                    //设置子标签项
                    //发送者
                    serializer.startTag(null, "sender");
                    serializer.text(sms.getSender());
                    serializer.endTag(null, "sender");
                    //接收着
                    serializer.startTag(null, "receiver");
                    serializer.text(sms.getReceiver());
                    serializer.endTag(null, "receiver");
                    //内容
                    serializer.startTag(null, "body");
                    serializer.text(sms.getBody());
                    serializer.endTag(null, "body");
                    //日期
                    serializer.startTag(null, "date");
                    serializer.text(sms.getDate());
                    serializer.endTag(null, "date");
                //每个短信的结束标签
                serializer.endTag(null, "sms");
            }
            //根标签:结束
            serializer.endTag(null, "smss");
            serializer.endDocument();
            fos.close();
            Toast.makeText(MainActivity.this, "备份完成", 0).show();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

你可能感兴趣的:(安卓开发之旅)