网上的写XML DEMO多半会忽略Context指针的问题 往往导致直接使用其代码会产生空指针错误 程序崩溃
而写的好的代码又太长 不便于阅读与学习 因而写了个完全能运行的写XML文件代码
写在最前面 openFileOutpu 的 path 参数 不能包括绝对路径 相对路径 貌似只能写文件名 否则会抛出异常 file not found
主界面代码
package com.example.writexmlproject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.content.Context;
public class MainActivity extends Activity {
private final Context context;
public MainActivity(){
this.context = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt=(Button)findViewById(R.id.exchang);
bt.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v)
{
EditText wr=(EditText)findViewById(R.id.wr);
String content=wr.getText().toString();
write w = new write(context);
w.Write("blog.xml",content);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.example.writexmlproject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import org.xmlpull.v1.XmlSerializer;
import android.content.Context;
import android.util.Xml;
public class write {
private Context context;
public write(Context context) {
this.context = context;
}
private String writeXml(String content) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("utf-8", true);
serializer.startTag("", "ControlWnd");
serializer.startTag("", "Control");
serializer.attribute("", "type", "CheckBox");
serializer.attribute("", "Name", "CheckBox1");
serializer.attribute("", "Checked", "true");
serializer.endTag("", "Control");
serializer.startTag("", "Control");
serializer.attribute("", "type", "TextBox");
serializer.attribute("", "Name", "TextBox1");
serializer.attribute("", "Text", content);
serializer.endTag("", "Control");
serializer.endTag("", "ControlWnd");
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
boolean Write(String path, String content) {
String txt = writeXml(content);
// TODO Auto-generated method stub
try {
// path="/sdcard"+path;
OutputStream os = context.openFileOutput(path, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(txt);
osw.close();
os.close();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
}
生成的XML文件在 /data/data/com.example.xxx/files 下
效果如下