0

I'm very new in XML, and I try to modify an xml file. Let me explain what I want do. I have an existing file, in wich are writed few lines, but i want to keep them and add other ones.

My example is not working in the way I want. It's delete every thing, and write a new XML.

What I need to read to know how to do that?

This is my java code:

public static void WriteFile(){
          try{
              XMLOutputFactory  xMLOutputFactory  = XMLOutputFactory.newFactory();
              XMLStreamWriter xMLStreamWriter = xMLOutputFactory.
                      createXMLStreamWriter(new FileOutputStream("src\\data\\orders.xml"));
              xMLStreamWriter.writeStartDocument("1.0");
              xMLStreamWriter.writeStartElement("products");
              xMLStreamWriter.writeStartElement("product");

              //set description
              xMLStreamWriter.writeStartElement("description");
              xMLStreamWriter.writeCharacters("Apple MacBook Air A 11.6 Mac OS X v10.7 Lion MacBook");
              xMLStreamWriter.writeEndElement();
               //end description

              //set price
              xMLStreamWriter.writeStartElement("price");
              xMLStreamWriter.writeAttribute("currency","USD");
              xMLStreamWriter.writeCharacters("999");
              xMLStreamWriter.writeEndElement();
              //end price

              xMLStreamWriter.writeEndElement();
              //end produtcs
              xMLStreamWriter.writeEndElement();
              //end produtc
              xMLStreamWriter.flush();
              xMLStreamWriter.close();
          }catch (Exception e){
              System.out.println(e.getMessage());
          }
      }
Silviu
  • 175
  • 5
  • 15

1 Answers1

-1

Your code uses XML Stream Writer to write some data in a file location. The fact that the file exists and happens to contain XML is irrelevant as your code will simply overwrite it.

What you do now is:

  1. write the new content

What you need is:

  1. read the content of the existing file
  2. write the old content
  3. write the new content
  4. save the file

For steps 2, 3 and 4 you could use a new file and then overwrite the old one.

  • Can you give me a littel example, please? – Silviu Sep 17 '15 at 14:04
  • Here is an example using DOM: http://stackoverflow.com/questions/6445828/how-do-i-append-a-node-to-an-existing-xml-file-in-java I suggest this one over StAX as it is simpler to parse in the exiting file. You can use StAX too of course but it's slightly more verbose. – Dragos.Cojocari Sep 21 '15 at 10:52