用序列化器生成xml文件

前端之家收集整理的这篇文章主要介绍了用序列化器生成xml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.itheima.xmlserializer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import com.itheima.createxml.domain.Message;

import android.os.Bundle;
import android.app.Activity;
import android.util.Xml;
import android.view.Menu;
import android.view.View;

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.初始化;实际开发中先判断sd卡是否存在
        File file = new File("sdcard/sms2.xml");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //enconding:指定用什么编码生成xml文件
            xs.setOutput(fos,"utf-8");

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

            for (Message sms : smsList) {
                xs.startTag(null,"sms");
                //生成body节点
                xs.startTag(null,"body");
                //再添加<body>就没有问题了,会解析的
                xs.text(sms.getBody() + "<body>");
                xs.endTag(null,"body");
                //生成data节点
                xs.startTag(null,"date");
                xs.text(sms.getDate());
                xs.endTag(null,"date");
                //生成type节点
                xs.startTag(null,"type");
                xs.text(sms.getType());
                xs.endTag(null,"type");
                //生成address节点
                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();
        } 
    }

}
原文链接:https://www.f2er.com/xml/296101.html

猜你在找的XML相关文章