在线咨询
微信咨询
服务热线
服务热线:15639912513
TOP
当前位置:
首页 > 新闻中心> 安卓课堂>使用StringBuilder写xml实例

使用StringBuilder写xml实例

发布时间:2020-01-04 浏览:3644次

本文主要是运用StringBuilder把数据写成xml的一个例子。下面是界面代码,只写了个button。

122.png

其中运用的onclick事件,而不是之前的查找id进行捕获按钮。

下面是java代码:

public class MainActivity extends AppCompatActivity {

    ArrayList<SMS> smsList = new ArrayList<SMS>();

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        for (int i = 0;i<30;i++){

            SMS sms = new SMS();

            sms.from="100"+i;

            sms.content="content"+i;

            sms.time="2020-1-4 10:53:"+i;

            smsList.add(sms);

        }

    }


     public void saveSMS(View v) throws Exception {

下面这个代码是实例化StringBuilder类,通过实例化,进行xhh操作,从而把数据写入xml里面。

        StringBuilder xhh = new StringBuilder();

        xhh.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");

        xhh.append("<SMSLIST>");

        for (SMS sms:smsList){

            xhh.append("<SMS>");

            xhh.append("<from>");

            xhh.append(sms.from);

            xhh.append("</from>");

            xhh.append("<content>");

            xhh.append(sms.content);

            xhh.append("</content>");

            xhh.append("<time>");

            xhh.append(sms.time);

            xhh.append("</time>");

            xhh.append("</SMS>");

        }

        xhh.append("</SMSLIST>");

        String xml = xhh.toString();

        FileOutputStream fos = openFileOutput("sms.xml",MODE_PRIVATE);

        fos.write(xml.getBytes());

        fos.close();

     }

}

122.png

这个图片是生成的xml文件。


TAG
3644
该内容对我有帮助