// 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.FileOutputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DOM4J_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
        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(XML_FILE);
        // transform from one dom to another dom
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new File(XSL_FILE)));
        DocumentResult res = new DocumentResult();
        t.transform(new DocumentSource(doc), res);
        Document doc2 = res.getDocument();
        // write out
        OutputFormat of = OutputFormat.createPrettyPrint();
        FileOutputStream fos = new FileOutputStream("/work/employees2.xml");
        XMLWriter xw = new XMLWriter(fos, of);
        xw.write(doc2);
        xw.close();
        fos.close();
    }
}
