There are three steps to learning XSLT on Java:
1- Pick a XSLT engine.
Each engine is slightly different, but for basic processing any will do.
Xalan has always worked well for me. To get started, all you need to do is download the Xalan jar(s) from here and put them in your project's classpath. The file you need is one of the xalan-j_X_X_X-bin-2jars
files.
Then use the following code to process a sample XML within a Java program (adapted from SimpleTransform.java, not tested):
public class SimpleTransform {
public static void main(String[] args) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource("transform.xslt"));
transformer.transform(new StreamSource("input.xml"), new StreamResult(new FileOutputStream("output.out")));
System.out.println("************* The result is in output.out *************");
} catch (Throwable t) {
t.printStackTrace();
}
}
}
2- Learn XPath.
XPath is the syntax used to select elements within an input XML file.
It also allows provided basic functions to do some processing. Although XPath is a major part of XSLT, it can be used independently to process XML files.
For example, Dom4j and most XML parsers provide the ability to select elements using the XPath syntax. I can't recommend any specific tutorial, but searching
XPath tutorial provides a number of good results.
3- Learn the XSLT format.
XSLT is simply XML. The XSLT specification can be found here.
There are plenty of tutorials out there. Just start from a simple example and build your knowledge from there. Some of the key points to remember:
- XSLT is based on a functional language. If you try to use it as a procedural language, you will end up with difficult to maintain XSLT files. Related question on that topic.
- You can't modify variables. You can declare and assign values to variables, but you can't modify them. I remember hitting a wall a few times because of this.