// 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.FileWriter;
import java.io.Writer;

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

import org.jdom2.transform.JDOMResult;
import org.jdom2.transform.JDOMSource;
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class JDOM2_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
        SAXBuilder b = new SAXBuilder();
        Document doc = b.build(XML_FILE);
        // transform from one dom to another dom
        Document xsl = b.build(XSL_FILE);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new JDOMSource(xsl));
        JDOMResult res = new JDOMResult();
        t.transform(new JDOMSource(doc), res);
        Document doc2 = res.getDocument();
        // write out
        XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
        Writer w = new FileWriter("/work/employees2.xml");
        w.write(fmt.outputString(doc2));
        w.close();
    }
}
