我想在现有的 xml 文件中插入一个新节点,但下面的代码再次插入所有节点。
如果文件存在,我会进行测试。如果没有,我创建一个新的 xml 文件并编写标签。如果存在,它也会创建节点,但方法错误。
//create a new file called "new.xml" in the SD card
File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/download/teste/audit.xml");
if (newxmlfile.exists()){
try{
fileos = new FileOutputStream(newxmlfile, true);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
} else {
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
}
//we create a XmlSerializer in order to write xml data
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fileos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "root");
serializer.startTag(null, "child1");
serializer.endTag(null, "child1");
serializer.startTag(null, "child2");
serializer.attribute(null, "attribute", "value");
serializer.endTag(null, "child2");
serializer.startTag(null, "child3");
serializer.text("some text inside child3");
serializer.endTag(null, "child3");
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
fileos.close();
Context context = getApplicationContext();
CharSequence text = "Save!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
结果是这样的:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<root>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
</root><?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<root>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
</root>
但我想要这样的结果:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<root>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
</root>
谢谢!