用 Java 进行 XSLT 处理?

如何使用 JDK 在 Java 中使用 XSLT 处理器转换 XML?

106983 次浏览

The Java standard library provides an (XSLT) transformation interface for XML parsing. See the API documentation for the classes javax.xml.transform.Transformer and javax.xml.transform.TransformerFactory.

I am new to xslt. Can anybody guide me how to xslt processing with java?

This depends on which Java-based XSLT processor you are using. Each XSLT processor has its own API.

For example, Saxon 6.5.5 (for XSLT 1.0) and Saxon 9.1.07 (for XSLT 2.0) are written in Java. The documentation is at http://www.saxonica.com/documentation/documentation.xml

Almost all XSLT processors have a command-line utility, which doesn't require writing a program in order to perform an XSLT transformation.

For example, here is: how to start a Saxon 9.x transformation from the command line.

Here is how I always use Saxon from the command-line:

java -Xms2048M  -Xmx10000M  -jar
C:\xml\Parsers\Saxon\Ver.9.1.0.7\J\saxon9.jar
-t  -repeat:1  -o %out%  %xml%  %xsl%  %param[ name=\"value\"]%

where %out% is the name of the output file, %xml% is the xml file, %xsl% is the primary xslt file and %param[ name=\"value\"]% is a name-value list of external parameters (I almost always leave this empty).

JAXP provides a implementation independent way of working with XSLT transformations. Here is the tutorial to get you started. If you are working with huge XSLT and/or working with multiple XSLT's then there is also an option of caching the parsed XSLT templates for performance reasons. This article explains how to cache xslt's

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.