// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class AppendXml {
    public static String load(String fnm) throws Exception {
        StringBuffer sb = new StringBuffer("");
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fnm)));
        String line;
        while((line = in.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        return sb.toString();
    }
    public static void write(PrintStream ps, String ind, Node parent) {
        switch (parent.getNodeType()) {
            case Node.ELEMENT_NODE :
                ps.println(ind + "<" + parent.getNodeName() + ">");
                NodeList childs = parent.getChildNodes();
                for (int i = 0; i < childs.getLength(); i++) {
                    write(ps, ind + "   ", childs.item(i));
                }
                ps.println(ind + "</" + parent.getNodeName() + ">");
                break;
            case Node.TEXT_NODE :
                if(!parent.getNodeValue().trim().equals("")) {
                    ps.println(ind + parent.getNodeValue().trim());
                }
                break;
            default :
                // nothing
        }
        return;
    }
    private static void show(String fnm) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(fnm);
        write(System.out, "", doc.getDocumentElement());
    }
    private static void showFake(String fnm) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(load(fnm) + "\n</all>")));
        write(System.out, "", doc.getDocumentElement());
    }
    private static void setup(String fnm) throws Exception {
        PrintStream ps = new PrintStream(new FileOutputStream(fnm));
        ps.println("<all>");
        ps.println("   <one>");
        ps.println("      A");
        ps.println("   </one>");
        ps.println("</all>");
        ps.close();
    }
    private static void setupFake(String fnm) throws Exception {
        PrintStream ps = new PrintStream(new FileOutputStream(fnm));
        ps.println("<all>");
        ps.println("   <one>");
        ps.println("      A");
        ps.println("   </one>");
        ps.close();
    }
    private static void append1(String fnm, String val) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(fnm);
        Element one = doc.createElement("one");
        one.appendChild(doc.createTextNode(val));
        doc.getDocumentElement().appendChild(one);
        write(new PrintStream(new FileOutputStream(fnm)), "", doc.getDocumentElement());
    }
    private static void approach1() throws Exception {
        setup("C:\\a1.xml");
        append1("C:\\a1.xml", "BB");
        append1("C:\\a1.xml", "CCC");
        show("C:\\a1.xml");
    }
    private static void append2(String fnm, String val) throws Exception {
        PrintStream ps = new PrintStream(new FileOutputStream(fnm, true));
        ps.println("   <one>");
        ps.println("      " + val);
        ps.println("   </one>");
        ps.close();
    }
    private static void approach2() throws Exception {
        setupFake("C:\\a2.xml");
        append2("C:\\a2.xml", "BB");
        append2("C:\\a2.xml", "CCC");
        showFake("C:\\a2.xml");
    }
    private static void append3(String fnm, String val) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        ps.println("   <one>");
        ps.println("      " + val);
        ps.println("   </one>");
        ps.println("</all>");
        ps.close();
        RandomAccessFile raf = new RandomAccessFile(fnm, "rw");
        long ix = raf.length() - 8;
        raf.seek(ix);
        byte[] b = new byte[8];
        raf.read(b);
        int i = 0;
        while(b[i] != '<') {
            ix++;
            i++;
        }
        raf.seek(ix);
        raf.write(baos.toByteArray());
        raf.close();
    }
    private static void approach3() throws Exception {
        setup("C:\\a3.xml");
        append3("C:\\a3.xml", "BB");
        append3("C:\\a3.xml", "CCC");
        show("C:\\a3.xml");
    }
    public static void main(String[] args) throws Exception {
        approach1();
        approach2();
        approach3();
    }
}
