生成的XML文件
package com.example.createxml;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<Message> msgs = new ArrayList<Message>();
for (int i = 0; i < 10; i++) {
Message msg = new Message("宁波" + i, System.currentTimeMillis() + "", 1 + "", Math.random() + "" + i);
msgs.add(msg);
}
final StringBuffer sb = new StringBuffer();
btn = (Button) findViewById(R.id.create);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<messages>");
for (Message m : msgs) {
sb.append("<message>");
sb.append("<address>");
sb.append(m.getAddress());
sb.append("</address>");
sb.append("<date>");
sb.append(m.getDate());
sb.append("</date>");
sb.append("<type>");
sb.append(m.getType());
sb.append("</type>");
sb.append("<body>");
sb.append(m.getBody());
sb.append("</body>");
sb.append("</message>");
}
sb.append("</messages>");
File file = new File(getFilesDir(), "info.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
package com.example.createxml;
/**
* Created by joy on 2015/12/20.
*/
public class Message {
public Message(String address, String date, String type, String body) {
this.address = address;
this.date = date;
this.type = type;
this.body = body;
}
private String address;
private String date;
private String type;
private String body;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}