Я хотел бы вставить новый узел в существующий xml-файл, но приведенный ниже код снова вставляет все узлы.Как вставить новый узел в существующий 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>
Спасибо!
Итак, проблема заключается в следующем: создается другой корень вместо использования существующего (в случае если файл уже содержит child1-3), правильно? Кстати в коде нет вставки child4-6. – sandrstar
Правильно. Я хочу: Если документ не существует, он создает структуру по умолчанию, а затем вставляет узел. И если документ существует, вставьте новый узел внутри корневого узла и не повторяйте структуру ' Xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>" ' –
Wesley
@ Уэсли: Может, пожалуйста, помогите мне с моей аналогичной проблемой? Http://stackoverflow.com/questions/21318966/adding-a-node-to-same-xml-file-on-sd-card-under-its-root- tag-in-android –