Search code examples
javaxmlstax

modify xml file with Stax API Java


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());
          }
      }

Solution

  • 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.