1:
package com.itheima.xmlserializer;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.View;
import android.widget.Toast;
import com.itheima.xmlserializer.po.SmsInfo;
public class XmlserializerActivity extends Activity {
private ArrayList<SmsInfo> infos = new ArrayList<SmsInfo>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int number = 135000;
for (int i = 0; i < 10; i++) {
infos.add(new SmsInfo(i, System.currentTimeMillis(), "短信" + i,
number + i + ""));
}
}
public void save(View view) {
XmlSerializer xmlSerializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(),
"config.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
xmlSerializer.setOutput(fos, "utf-8");
xmlSerializer.startDocument("utf-8", true);
xmlSerializer.startTag(null, "smss");
for (SmsInfo info : infos) {
xmlSerializer.startTag(null, "sms");
xmlSerializer.attribute(null, "id", info.getId() + "");
xmlSerializer.startTag(null, "date");
xmlSerializer.text(info.getDate() + "");
xmlSerializer.endTag(null, "date");
xmlSerializer.startTag(null, "address");
xmlSerializer.text(info.getAddress());
xmlSerializer.endTag(null, "address");
xmlSerializer.startTag(null, "body");
xmlSerializer.text(info.getBody());
xmlSerializer.endTag(null, "body");
xmlSerializer.endTag(null, "sms");
}
xmlSerializer.endTag(null, "smss");
xmlSerializer.endDocument();
fos.close();
Toast.makeText(this, "保存成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "保存失败", 0).show();
}
}
}
2“
package com.itheima.xmlserializer.po;
public class SmsInfo {
private int id;
private long date;
private String body;
private String address;
public SmsInfo() {
super();
// TODO Auto-generated constructor stub
}
public SmsInfo(int id, long date, String body, String address) {
super();
this.id = id;
this.date = date;
this.body = body;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:onClick="save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存xml文件" />
</LinearLayout>