package jie.java.android.xmlfiletest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
public class XmlFileTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
writeXmlFile();
readXmlFile();
}
private int writeXmlFile() {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Log.d("xml", "mounted");
}
else {
Log.d("xml", "not mount.");
}
File file = new File(Environment.getExternalStorageDirectory(), "my.xml");
try {
file.createNewFile();
}
catch (IOException e) {
Log.e("xml", "file.createNewFile() exception." + e.getMessage());
return -1;
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
}
catch (FileNotFoundException e) {
Log.e("xml", "FileOutputStream exception.");
return -1;
}
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(os, "UTF-8");
serializer.startDocument(null, true);
serializer.startTag(null, "root");
serializer.attribute(null, "attr", "123");
serializer.text("hello");
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
os.close();
}
catch (Exception e) {
Log.e("xml", "serializer exception.");
}
return 0;
}
private int readXmlFile() {
File file = new File(Environment.getExternalStorageDirectory(), "my.xml");
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xp = factory.newPullParser();
FileInputStream is = new FileInputStream(file);
xp.setInput(is, "UTF-8");
int type = xp.getEventType();
while(type != XmlPullParser.END_DOCUMENT) {
if(type == XmlPullParser.START_DOCUMENT) {
}
else if(type == XmlPullParser.START_TAG) {
Log.d("xml", "start tag:" + xp.getName());
Log.d("xml", "attr: " + xp.getAttributeName(0) + " value:" + xp.getAttributeValue(0));
}
else if(type == XmlPullParser.TEXT) {
Log.d("xml", "text:" + xp.getText());
}
type = xp.next();
}
is.close();
}
catch (XmlPullParserException e) {
return -1;
}
catch (IOException e) {
return -1;
}
return 0;
}
}