0

I'm using the code below. However I want to append new XML to same TXT file one below the other when ever I run the code. is that possible using the JDOM. Pls help me..

xmlOutput.output(doc, new FileWriter("c:\updated.txt")); is the one that needs to be modified?

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class Replacer {
    public static void main(String[] args) {
          try {

            SAXBuilder builder = new SAXBuilder();
            File xmlFile = new File("c:\\file.xml");
            String temp = "1234567";

            Document doc = (Document) builder.build(xmlFile);
            Element rootNode = doc.getRootElement();

            System.out.println("Root Node is --> "+rootNode);

            Element ShipmentLines = rootNode.getChild("ShipmentLines");

            Element ShipmentLine = ShipmentLines.getChild("ShipmentLine");

            Element Containers = rootNode.getChild("Containers");

            Element Container = Containers.getChild("Container");


            ShipmentLine.getAttribute("OrderNo").setValue(temp);


            Container.getAttribute("ContainerScm").setValue(temp);

            XMLOutputter xmlOutput = new XMLOutputter();

            xmlOutput.setFormat(Format.getPrettyFormat());
            xmlOutput.output(doc, new FileWriter("c:\\updated.txt"));

          } catch (IOException io) {
            io.printStackTrace();
          } catch (JDOMException e) {
            e.printStackTrace();
          }
}
}
amukhachov
  • 5,822
  • 1
  • 41
  • 60
user1669488
  • 227
  • 1
  • 2
  • 10

1 Answers1

1

JDOM does not directly support appending to existing files, but it only requires a small amount of extra code. Just write your output to a StringWriter, grab the string, then append the string to the existing file. One possible implementation:

XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
StringWriter out = new StringWriter();
xmlOutput.output(doc, out);
FileUtils.writeStringToFile(new File("c:\\updated.txt"), out.toString(), true);

I am cheating here using the commons-io FileUtils class. See Append data into a file using Apache Commons I/O

If commons-io is not available or practical for your app, then write your own append-string-to-file method.

Community
  • 1
  • 1
Guido Simone
  • 7,912
  • 2
  • 19
  • 21