// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package xmlproc;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

public class W3CDOM_XSLT {
    private final static String XML_FILE = "/work/employees.xml";
    private final static String XSL_FILE = "/work/employees.xsl";
    public static void main(String[] args) throws Exception {
        // read from file to DOM tree
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File(XML_FILE));
        // transform from one dom to another dom
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new File(XSL_FILE)));
        Document doc2 = db.newDocument();
        t.transform(new DOMSource(doc), new DOMResult(doc2));
        // write out
        DOMImplementation impl = DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0");
        DOMImplementationLS feature = (DOMImplementationLS)impl.getFeature("LS","3.0");
        LSSerializer ser = feature.createLSSerializer();
        ser.getDomConfig().setParameter("format-pretty-print", true);
        LSOutput output = feature.createLSOutput();
        Writer w = new FileWriter("/work/employees2.xml");
        output.setCharacterStream(w);
        ser.write(doc2, output);
        w.close();
    }
}
