在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();
}