2

I am writing some data to an XML file.

Here is the code:

    try {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("company");
    doc.appendChild(rootElement);

    // staff elements
    Element staff = doc.createElement("Staff");
    rootElement.appendChild(staff);

    // set attribute to staff element
    Attr attr = doc.createAttribute("id");
    attr.setValue("1");
    staff.setAttributeNode(attr);

    // shorten way
    // staff.setAttribute("id", "1");

    // firstname elements
    Element firstname = doc.createElement("firstname");
    firstname.appendChild(doc.createTextNode("yong"));
    staff.appendChild(firstname);

    // lastname elements
    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("mook kim"));
    staff.appendChild(lastname);

    // nickname elements
    Element nickname = doc.createElement("nickname");
    nickname.appendChild(doc.createTextNode("mkyong"));
    staff.appendChild(nickname);

    // salary elements
    Element salary = doc.createElement("salary");
    salary.appendChild(doc.createTextNode("100000"));
    staff.appendChild(salary);

    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("file.xml"));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("File saved!");

  } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();
  }
}

This code writes the XML data to the "file.xml". If I already have a "file.xml" file, what is the best way to append the XML data to the file? Will I need to rewrite the whole above code, or is it easy to adapt the code?

informatik01
  • 16,038
  • 10
  • 74
  • 104
user2381256
  • 101
  • 2
  • 2
  • 5

2 Answers2

0

Yes - you're dealing with DOM, so you have to have the whole file in memory. Alternative is StAX.

0
StreamResult result = new StreamResult(new File("file.xml"));

Check this line. Replace the above line with this.

StreamResult result = new StreamResult(new FileOutputStream("file.xml", true));

By default the second parameter is false. True means it will append to file, false means it will overwrite it.