XSLT processing with Java?

Venkat picture Venkat · Jan 5, 2011 · Viewed 96.2k times · Source

How to transform XML with XSLT processor in Java using the JDK?

Answer

Askar Kalykov picture Askar Kalykov · Jun 22, 2011

Here is sample for using java api for transformer, as @Raedwald said:

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class TestMain {
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Source xslt = new StreamSource(new File("transform.xslt"));
        Transformer transformer = factory.newTransformer(xslt);

        Source text = new StreamSource(new File("input.xml"));
        transformer.transform(text, new StreamResult(new File("output.xml")));
    }
}

The input can also be from a string or DOMSource, the output can be to a DOMSource etc.