android 中生成xml文件
在Android中生成xml文件真的很簡單,下面提供2中方法,一種是通過String寫入到文件,另外一種是通過XML 的 XmlSerializer.
以後遇到Android寫xml內容就不會困惑了
1、通過string寫入文件
String name=mEtName.getText().toString(); String age=mEtAge.getText().toString(); String Id=mEtID.getText().toString(); File file=new File(Environment.getExternalStorageDirectory(),"info.xml"); try{ FileOutputStream fos=new FilOutputStream(file); StringBuffer sb=new StringBuffer(); //開始寫入xml裏的內容 sb.append("<?xml version=‘1.0‘ encoding=‘utf-8‘ standalone=‘true‘ ?>"); sb.append("<info>"); sb.append("<student id=‘"+id+"‘>"); sb.append("<name>"+name+"</name>"); sb.append("<age>"+age+"</age>"); sb.append("</student>"); sb.append("</info>"); fos.write(sb.toString().getBytes()); fos.close;//關閉流 }catch(Exception e){ e.printStackTrace(); }
2、通過Android的util裏的XML類來寫入
String name=.getText().toString()String age=.getText().toString()String Id=.getText().toString()
XmlSerializer xmlSerializer=XML.newSerializer();
try{
FileOutputStream fos=new FileOutputStream(new File(Environment.getExtrernalStorageDirectory,"info2.xml"));
xmlSerializer.setOutput(fos,"utf-8");
xmlSerializer.setStartDocument("utf-8",true);
xmlSerializer.setStartTag(null,"info");
xmlSerializer.setStartTag(null,"student");
xmlSerializer.attribute(null,"id",Id);
xmlSerializer.setStartTag(null,"name");
xmlSerializer.text(name);
xmlSerializer.setEndTag(null,"name");
xmlSerializer.setStartTag(null,"age");
xmlSerializer.text(age);
xmlSerializer.setEndTag(null,"age");
xmlSerializer.setEndTag(null,"student");
xmlSerializer.setEndTag(null,"info");
xmlSerializer.setEndDocument();
fos.close(); //關閉流
}catch(Exception e){
e.printStackTrace();
}
本文出自 “YuanGuShi” 博客,請務必保留此出處http://cm0425.blog.51cto.com/10819451/1937304
android 中生成xml文件