前端之家收集整理的这篇文章主要介绍了
XML的序列化,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public class Xml extends Activity {
private List<SmsInfo> smsInfos;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xml);
//模拟短信信息的初始化
SmsInfo smsinfo1=new SmsInfo("110","你好啊1",""+System.currentTimeMillis(),1);
SmsInfo smsinfo2=new SmsInfo("111","你好啊2",1);
SmsInfo smsinfo3=new SmsInfo("120","你好啊3",2);
smsInfos=new ArrayList<SmsInfo>();
smsInfos.add(smsinfo1);
smsInfos.add(smsinfo2);
smsInfos.add(smsinfo3);
}
//模拟保存
public void click(View view){
try {
XmlSerializer serializer = android.util.Xml.newSerializer();//得到一个新的xml序列化器
File file = new File(getFilesDir(),"sms.xml");
FileOutputStream fos = new FileOutputStream(file);
serializer.setOutput(fos,"utf-8");//文件的编码格式
//第二个参数 :是否是独立的,不是独立的就是依赖于另外一些文件
serializer.startDocument("utf-8",true);//文件里面内容的编码
serializer.startTag(null,"smss");//最外层的根节点
for (SmsInfo smsInfo : smsInfos) {
serializer.startTag(null,"sms");//每一条短信的节点
serializer.startTag(null,"content");
serializer.text(smsInfo.getContent());
serializer.endTag(null,"content");
serializer.startTag(null,"time");
serializer.text(smsInfo.getTime());
serializer.endTag(null,"time");
serializer.startTag(null,"type");
serializer.text(smsInfo.getType()+"");
serializer.endTag(null,"type");
serializer.endTag(null,"sms");
}
serializer.endTag(null,"smss");
serializer.endDocument();
fos.close();//写入流里面,最后关闭掉
} catch (Exception e) {
}
}
}