3
我試圖使用xmlSerializer創建一個xml文件。這將從ui獲取2個值,用戶名爲&的密碼。所以,每個條目都會附加到xml文件中。 如果我使用下面的代碼,比只保留最後的入門在編寫XML時遇到困難
FileOutputStream fileos= getApplicationContext().openFileOutput(xmlFile, Context.MODE_PRIVATE);
再說一次,如果我使用MODE_APPEND,而不是私人要比通吃式的版本等給出的XML標記。
FileOutputStream fileos= getApplicationContext().openFileOutput(xmlFile, Context.MODE_APPEND);
但我需要追加條目只 - 這是XML文件中的用戶名和密碼標記。
下面是我的總代碼:
public class MainActivity extends Activity
{
EditText txtKey;
EditText txtValue;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtKey = (EditText)findViewById(R.id.txtvwKey);
txtValue = (EditText)findViewById(R.id.txtvwValue);
btn = (Button)findViewById(R.id.btnSave);
}
@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;
}
public void saveClk(View v)
throws FileNotFoundException, SAXException
{
final String xmlFile="userMemo.xml";
String key= txtKey.getText().toString();
String val= txtValue.getText().toString();
try {
FileOutputStream fileos= getApplicationContext().openFileOutput(xmlFile, Context.MODE_APPEND);
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8",true);
xmlSerializer.startTag(null, "userData");
xmlSerializer.startTag(null, "userName");
xmlSerializer.text(key);
xmlSerializer.endTag(null,"userName");
xmlSerializer.startTag(null,"password");
xmlSerializer.text(val);
xmlSerializer.endTag(null, "password");
xmlSerializer.endTag(null, "userData");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite=writer.toString();
fileos.write(dataWrite.getBytes());
fileos.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我應該如何去解決呢?