//建立xml的序列器
XmlSerializer xs=Xml.newSerializer();
//使用安卓getFilesDir()方法存入本手机的路径,注意这里要抛异常
File file=new File(getFilesDir(),name1+".xml");
FileOutputStream os= new FileOutputStream(file);
xs.setOutput(os, "utf-8");
//有开始一定有结束
xs.startDocument("utf-8", true);
xs.startTag(null, "student");
xs.startTag(null, "name");
xs.text(name1);
xs.endTag(null, "name");
xs.startTag(null, "number");
xs.text(nummber1);
xs.endTag(null, "number");
xs.startTag(null, "sex");
xs.text(sex1);
xs.endTag(null, "sex");
xs.endTag(null, "student");
xs.endDocument();
os.close();
//怎样读取xml文件
//使用pull解析方式
XmlPullParser xp=Xml.newPullParser();
FileInputStream fs=new FileInputStream(file);
xp.setInput(fs, "utf-8");
int type=xp.getEventType();
StringBuilder sb=new StringBuilder();
while(type != XmlPullParser.END_DOCUMENT){
if(type==XmlPullParser.START_TAG){
if("name".equals(xp.getName())){
sb.append("姓名 :"+xp.nextText() + "\n");
}else if("number".equals(xp.getName())){
sb.append("学号:"+xp.nextText()+"\n");
}else if("sex".equals(xp.getName())){
sb.append("性别" + xp.nextText() +"\n");
}
}
type=xp.next();
}
fs.close();
网友评论