xml文件生成的方式:
生成xml的样式
1、手动生成:
生成的xml文件可以保存在不同的地方,此处以sd卡为例
//拿到sd卡的状态
String state = Environment.getExternalStorageState();
//判断当前状态是否可用
if(state.equals(Environment.MEDIA_MOUNTED)){
//拿到sd卡的路径
String path = Environment.getExternalStorageDirectory()+"/sms.xml";
File file = new File(path);
try {
FileOutputStream fos = new FileOutputStream(file);
StringBuilder sb = new StringBuilder();
//添加头
sb.append("<?xml version = ‘1.0‘ encoding = ‘utf-8‘?>");
sb.append("<Smses>");
//循环拿到list中的值,此处没有列出
for(int i=0;i<list.size() ;i++){
sb.append("<sms>");
sb.append("<address>" + list.get(i).getAddress() + "</address>");
sb.append("<body>" + list.get(i).getBody() + "</body>");
sb.append("<date>" + list.get(i).getDate() + "</date>");
sb.append("</sms>");
}
sb.append("</Smses>");
fos.write(sb.toString().getBytes());
fos.close();
Toast.makeText(this, "xml文件创建成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "xml文件创建失败", 0).show();
}
}else{
Toast.makeText(this, "sd卡不可用", 0).show();
}
2、利用系统的api生成:
//拿到sd卡的状态
String state = Environment.getExternalStorageState();
//判断sd卡是否可用
if(state.equals(Environment.MEDIA_MOUNTED)){
//文件存在时直接写入,不存在时会重新创建文件
String path = Environment.getExternalStorageDirectory() +"/sms.xml";
File file = new File(path);
try {
//创建xml文件生成器
XmlSerializer serializer = Xml.newSerializer();
FileOutputStream fos = new FileOutputStream(file);
serializer.setOutput(fos, "utf-8");
//生成xml文件的头部分
serializer.startDocument("utf-8", true);
//生成开始节点
serializer.startTag(null, "Smses");
//此处是拿取list中的值,没有列出list
for(int i = 0;i<list.size();i++){
serializer.startTag(null, "sms");
serializer.startTag(null, "address");
serializer.text(list.get(i).getAddress());
serializer.endTag(null, "address");
serializer.startTag(null, "body");
serializer.text(list.get(i).getBody());
serializer.endTag(null, "body");
serializer.startTag(null, "date");
serializer.text(list.get(i).getDate());
serializer.endTag(null, "date");
serializer.endTag(null, "sms");
}
//结束节点(开始节点和结束节点一一对应)
serializer.endTag(null, "Smses");
//此处会完全关闭,所以不用再关闭流
serializer.endDocument();
Toast.makeText(this, "xml文件生成成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "xml文件生成失败", 0).show();
}
}else{
Toast.makeText(this, "sd卡不可用", 0).show();
}
}