废话少说,直接看代码
package cn.qing.xmltest;
import java.io.*;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.*;
import android.util.*;
import android.widget.TextView;
public class wrXml extends Activity {
/** Called when the activity is first created. */
private String appDir;
private String xmlFileName;
StringBuilder sb;
TextView tv;
public wrXml(){
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appDir = this.getApplicationContext().getFilesDir().getAbsolutePath();
xmlFileName = appDir + "/test.xml";
tv = new TextView(this);
sb = new StringBuilder();
writeXml();
tv.setText(sb.toString());
setContentView(tv);
}
private void writeXml() {
File xmlFile = new File(xmlFileName);
try {
xmlFile.createNewFile();
} catch (IOException e) {
Log.e("IOException", "exception in createNewFile() method");
}
FileOutputStream fileos = null;
try {
fileos = new FileOutputStream(xmlFile);
} catch (FileNotFoundException e) {
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fileos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",true);
serializer.startTag(null, "root");
serializer.startTag(null, "child1");
serializer.endTag(null, "child1");
serializer.startTag(null, "child2");
serializer.attribute(null, "attribute", "value");
serializer.endTag(null, "child2");
serializer.startTag(null, "child3");
serializer.text("some text inside child3");
serializer.endTag(null, "child3");
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
fileos.close();
sb.append("file has been created");
} catch (Exception e) {
Log.e("Exception", "error occurred while creating xml file");
sb.append("Create file error");
}
}
}