在Android中把内容写到XML文件中
saveXmlButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
List<StudentInfo> studentInfos = StudentInfo.initStudentInfos();
try {
FileOutputStream os = openFileOutput(fileName, MODE_PRIVATE);
//获取XmlSerializer对象
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
org.xmlpull.v1.XmlSerializer xmlSerializer = factory.newSerializer();
//设置输出流对象
xmlSerializer.setOutput(os, "utf-8"); /*
* startDocument(String encoding, Boolean standalone)encoding代表编码方式
* standalone 用来表示该文件是否呼叫其它外部的文件。
* 若值是 ”true” 表示没有呼叫外部规则文件,若值是 ”false” 则表示有呼叫外部规则文件。默认值是 “yes”。
*/
xmlSerializer.startDocument("utf-8", true);
xmlSerializer.startTag("myNameSpace", "Students"); for (StudentInfo studentInfo : studentInfos) {
xmlSerializer.startTag(null, "student");
xmlSerializer.attribute(null, "id", studentInfo.getId()+"");
xmlSerializer.startTag(null, "name");
xmlSerializer.text(studentInfo.getName());
xmlSerializer.endTag(null, "name"); xmlSerializer.startTag(null, "address");
xmlSerializer.text(studentInfo.getAddress());
xmlSerializer.endTag(null, "address"); xmlSerializer.startTag(null, "phone");
xmlSerializer.text(studentInfo.getPhone());
xmlSerializer.endTag(null, "phone"); xmlSerializer.endTag(null, "student");
}
xmlSerializer.endTag("myNameSpace", "Students");
xmlSerializer.endDocument();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});