xml格式保存信息到文件

前端之家收集整理的这篇文章主要介绍了xml格式保存信息到文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.example.xml_duanxinbeifen;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


import org.xmlpull.v1.XmlSerializer;


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


import com.example.xml_duanxinbeifen.domain.SmsInfo;


public class MainActivity extends Activity {
private List<SmsInfo> smsinfos;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsinfos = new ArrayList<SmsInfo>();
Random random = new Random();
// 创建十条短信
for (int i = 0; i < 10; i++) {
smsinfos.add(new SmsInfo(System.currentTimeMillis(),random
.nextInt(2) + 1,"你好" + i,Integer.toString(i * 100 + i)));
}


}


public void backMessage(View view) {
XmlSerializer serializer = Xml.newSerializer();
// File file = new File(this.getFilesDir(),"sms.xml");
File file = new File("/data/data/com.example.xml_duanxinbeifen/sms.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
// 初始化序列化器,指定文件和编码
serializer.setOutput(fos,"utf-8");
// true表示独立的文件
serializer.startDocument("utf-8",true);
// 开始节点
serializer.startTag(null,"smss");

for(SmsInfo smsInfo:smsinfos)
{
serializer.startTag(null,"sms");
// 添加标签,以starttag开头,endtag结尾,中间的内容属性text设置
serializer.startTag(null,"date");
serializer.text(smsInfo.getDate()+ "");
serializer.endTag(null,"date");

serializer.startTag(null,"body");
serializer.text(smsInfo.getBody());
serializer.endTag(null,"body");


serializer.startTag(null,"type");
serializer.text(smsInfo.getType() + "");
serializer.endTag(null,"type");


serializer.startTag(null,"address");
serializer.text(smsInfo.getAddress());
serializer.endTag(null,"address");


serializer.endTag(null,"sms");


}
serializer.endTag(null,"smss");
serializer.endDocument();
fos.close();
Toast.makeText(this,"备份成功",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(this,"备份失败",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

}

结果如图所示


文件导出后,打开文件内容如下

猜你在找的XML相关文章