序列化器生成XML文件保存信息

来源:互联网 发布:怎么样求助网络捐款 编辑:程序博客网 时间:2024/06/03 20:21
先是属性封装
public class Message {

    private String body;
    private String date;
    private String address;
    private String type;
    public String getBody() {
        return body;
    }
    public void setBody(String body) {
        this.body = body;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Message(String body, String date, String address, String type) {
        super();
        this.body = body;
        this.date = date;
        this.address = address;
        this.type = type;
    }


}



然后是序列化器生成XML存储信息


public class MainActivity extends Activity {

    List<Message> smsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 虚拟10条短信
        smsList = new ArrayList<Message>();
        for (int i = 0; i < 10; i++) {
            Message sms = new Message("小志好棒" + i, System.currentTimeMillis()
                    + "", "138" + i + i, "1");
            smsList.add(sms);
        }
    }

    public void click(View v){
        //使用xml序列化器生成xml文件
        //1.拿到序列化器对象
        XmlSerializer xs = Xml.newSerializer();
        //2.初始化
        File file = new File("sdcard/sms2.xml");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //enconding:指定用什么编码生成xml文件
            xs.setOutput(fos, "utf-8");

            //3.开始生成xml文件
            //enconding:指定头结点中的enconding属性的值
            xs.startDocument("utf-8", true);

            xs.startTag(null, "message");

            for (Message sms : smsList) {
                xs.startTag(null, "sms");

                xs.startTag(null, "body");
                xs.text(sms.getBody() + "<body>");
                xs.endTag(null, "body");

                xs.startTag(null, "date");
                xs.text(sms.getDate());
                xs.endTag(null, "date");

                xs.startTag(null, "type");
                xs.text(sms.getType());
                xs.endTag(null, "type");

                xs.startTag(null, "address");
                xs.text(sms.getAddress());
                xs.endTag(null, "address");

                xs.endTag(null, "sms");
            }

            xs.endTag(null, "message");

            //告诉序列化器,文件生成完毕
            xs.endDocument();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
0 0