Best way to set xslt processor in Java?

2019-08-15 13:19发布

问题:

I have a simple program which have to make xslt transformation of given xml(>1GB).

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println(
            "Usage: java Transform [xmlfile] [xsltfile]");
        System.exit(1);
    }

    File xmlFile = new File(args[0]);
    File xsltFile = new File(args[1]);

    // JAXP reads data using the Source interface
    Source xmlSource = new StreamSource(xmlFile);
    Source xsltSource = new StreamSource(xsltFile);

    // the factory pattern supports different XSLT processors
    TransformerFactory transFact =
            TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);

    trans.transform(xmlSource, new StreamResult(System.out));
}

I want to use Xalan 2.7.1 so from the documentation I read:

Finally, if JAXP cannot find an implementation class from any of the three locations, it uses its default implementation of TransformerFactory. To summarize, here are the steps that JAXP performs when attempting to locate a factory:

  1. Use the value of the javax.xml.transform.TransformerFactory system property if it exists.
  2. If JRE/lib/jaxp.properties exists, then look for a javax.xml.transform.TransformerFactory=ImplementationClass entry in that file.
  3. Use a JAR file service provider to look for a file called META-INF/services/javax.xml.transform.TransformerFactory in any JAR file on the CLASSPATH.
  4. Use the default TransformerFactory instance. (Implementation of a JAXP1.1 TransformerFactory for Translets.) от com.sun.org.apache.xalan.internal.xsltc.trax

So if I put Xalan-2.7.1.jar on the classpath (3) will be hit and everything will be OK. But I am wondering which is the best way to define TransformerFactoryImpl?

I think as a variant to create jaxp.properties file and to put in the resource dir and in it to specify

factoryImpl=org.apache.xalan.processor.TransformerFactoryImpl

and then to set the javax.xml.transform.TransformerFactoryproperty in the code. In that way I when the implantation of the processor is changed only the properties file will be changed.

But this complicate the logic and I am wondering if I change the implementation JVM will find the new jar on the classpath and will other implementation be used. So is there a good reason to choose the properties decision or just adding the proper jar will fix all the problems? What will happen if other jar comes with transitive dependency to Saxon for example and I do not use the properties way?

标签: java xml xslt jar