how to append data to an xml file using jdom and java

I was wondering if someone could help append data to an XML file. Below, I have code where it grabs data from another xml file, does some logic changing, and writes the changes to a new output file. However, looking through this api

Im having trouble understanding which method does appending. It seems like all of them creates a new XML file doc/overwrites an existing one if it exists. Im trying to append tags to the new file as I loop.

        for(int i = 0; i < itemList.size(); i++){

            //get the specific item node 
            Element item = (Element)itemList.get(i);

            //there are some non item nodes so need this check

                //do some logic changing to the tags


                boolean exists = (new File("/Users/davidyu/Desktop/file2.xml")).exists();
                //if file exists
                    System.out.println("in here1");
                    System.out.println("in here2");
                    xmlOutput.output(doc, new FileWriter("/Users/davidyu/Desktop/file2.xml"));


What I`m basically trying to do, is write a new item tag into the file after every loop iteration. That item tag should contain the new childNodes "Q" and "A".

How can I do this?


Given that you're doing this in a loop, it would make sense to load the file once before the start of the loop, then go through the loop and add elements to the document as you go, then save it again after the loop. If the file doesn't exist beforehand, create a new document (just in memory, as you'll save it later) with whatever structure you need - e.g. just an appropriate root element. You'll need to work out where you want to add your new elements, of course.

There's no simple way of adding elements to an existing XML file without first loading the existing file. (While you could potentially do it in a streaming fashion, that's likely to be much more complicated to code.)


Is it possible to identify, probably using reflection, whether some method within a specific java class calls another method at build time? Let's say that I have ClassA that declares methodA1() ...

I am using Apache Active MQ with Spring..... the problem I am facing is that I am creating producer on one machine let say Machine1 and I am creating one consumer on second machine let say Machine2... ...

I am trying to pass dimensions to a Java Swing JPanel creator class. No luck so far. I even put the contentPane.setPreferredSize(new Dimension(intWidth, intHeight)); in a try / catch block and I did ...

To illustrate my point: I have Name Age and Address of 4 people [Sam, 23, nj], [Nome, 25, ny], [Sim, 20, pa], [Jack, 12, pa] I need to send these 4 rows to the java side. I am familiar with java ...