0

how can i add data to an xml file and append to it ohter data if it exists ?

i tried the following but this code only creates one node of values and does not append to the file. it always removes the existing one and add the new one to it.

import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        Question quest = new Question("Mouhib 9a7boun ?", "EYY");
        try {
            FileOutputStream fos = new FileOutputStream(new File("./quest.xml"));
            XMLEncoder encoder  = new XMLEncoder(fos);
            encoder.writeObject(quest);
            encoder.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
3
  • That class doesn't support appending. Its purpose is to write an xml representation of the current object graph. You should be writing something like ArrayList<Question> if you need to add Commented May 15, 2022 at 14:10
  • Please refer to this: Add new element to xml file with Java DOM Commented May 15, 2022 at 16:52
  • Please refer to this question Add new element to xml file with Java DOM Commented May 15, 2022 at 16:53

2 Answers 2

0

If you want to append addtional data to an existing file you can use FileOutputStream(File file, boolean append).

BUT this will not lead to a valid xml-file.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use XML DOM editing methods: XML DOM Add Nodes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.