手动拼接字符串
File file = new File(getFilesDir(), "xaioer.xml");
try {
OutputStream os = new FileOutputStream(file);
StringBuilder build = new StringBuilder();
build.append("<?xml version='1.0' encoding='utf-8' ?>");
build.append("<student>");
build.append("<name>");
build.append("xiaoer");
build.append("</name>");
build.append("</student>");
os.write(build.toString().getBytes());
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XmlSerializer
try {
File f = new File(getFilesDir(), "xiaoer.xml");
OutputStream os = new FileOutputStream(f);
XmlSerializer s = Xml.newSerializer();
s.setOutput(os, "utf-8");
s.startDocument("utf-8", true);
s.startTag(null, "student");
s.text("haha");
s.endTag(null, "student");
s.endDocument();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
使用的是Xmlpullparser
try {
//创建工厂
XmlPullParserFactory fac = XmlPullParserFactory.newInstance();
//设置支持名称空间的解析
fac.setNamespaceAware(true);
XmlPullParser pull = fac.newPullParser();
pull.setInput(new FileReader(new File(getFilesDir(),"xiaoer.xml")));
StringBuilder b = new StringBuilder();
// 查看类型 事件驱动的
int type = pull.getEventType();
//如果不是查询到了 pull.END_DOCUMENT 文档的结束 那么将指针指向下一个type = pull.next();
//pull.getText()得到对应标签中的文本 pull.getName();得到标签的名字
while(type!= pull.END_DOCUMENT) {
if ( type == pull.TEXT ) {
b.append(pull.getText());
}
type = pull.next();
}
Log.e("xiaoer", "sb");
Log.e("xiaoer", b.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("xiaoer",e.getMessage());
}