[Student{clazz='j2307',name='张三丰',sex='男',age='25'},Student{clazz='j2307'',name='周芷若',sex='女',age='23'}]
List<Student> students =new ArrayList<>();
// 创建xml文件
public void createXML(View view){
//判断要生成的数据是否存在
if(students != null && students.size() >0){
try {
String nameSpace = "";
//获取一个输出流对象,文件保存在files下
File file = new File(getExternalFilesDir(null).getAbsolutePath(),"student.xml");
FileOutputStream fileOutputStream = new FileOutputStream(file);
//定义一个生成xml文件的对象
XmlSerializer xmlSerializer = Xml.newSerializer();
//xml文件输出地址
xmlSerializer.setOutput(fileOutputStream,"UTF-8");
//设置开始文档抬头
xmlSerializer.startDocument("UTF-8",true);
//文档的开始标签
xmlSerializer.startTag(nameSpace,"students");
//遍历数据生成每一项
for(Student student : students){
xmlSerializer.startTag(nameSpace,"student");
xmlSerializer.attribute(nameSpace,"class",student.clazz);
xmlSerializer.startTag(nameSpace,"name");
xmlSerializer.text(student.name);
xmlSerializer.endTag(nameSpace,"name");
xmlSerializer.startTag(nameSpace,"sex");
xmlSerializer.text(student.sex);
xmlSerializer.endTag(nameSpace,"sex");
xmlSerializer.startTag(nameSpace,"age");
xmlSerializer.text(student.age);
xmlSerializer.endTag(nameSpace,"age");
xmlSerializer.endTag(nameSpace,"student");
}
//结束文档标签
xmlSerializer.endTag(nameSpace,"students");
xmlSerializer.endDocument();
fileOutputStream.close();
Toast.makeText(getApplication(),"生成xml文件成功!",Toast.LENGTH_SHORT).show();文章来源:https://www.toymoban.com/news/detail-592107.html
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplication(),"生成xml文件失败!"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}文章来源地址https://www.toymoban.com/news/detail-592107.html
到了这里,关于Android:生成XML文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!