Using Xalan along with Saxon

I use Xalan in my application, but you need to use Saxon with a reference implementation to create test output for comparison. I want to use them during unit tests. However, as soon as I add the Saxon dependency to the .pom project, the application seems to use Saxon for all xslt and XPath operations during the tests:

<dependency> <groupId>net.sf.saxon</groupId> <artifactId>Saxon-HE</artifactId> <version>9.4</version> <scope>test</scope> </dependency> 

This causes the main application to crash when generating output due to different XPath behavior. When starting the main application outside the scope of the scan, it works.

How to run the main application using Xalan, but tests using Saxon during tests?

I tried setting the following property before running the Xalan and Saxon parts:

 System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl "); System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl"); 

I also tried putting parts of Xalan and Saxon in different projects, and I also tried using them as from a third project, with the same result.

+6
source share
2 answers

Avoid using the JAXP factory mechanism to select your conversion engine. Instead, load the engine that you want explicitly: it is much more reliable and much faster. For Saxon, replace the call with

 TransformerFactory.newInstance() 

from

 new net.sf.saxon.TransformerFactoryImpl() 

and for using Xalan

 new org.apache.xalan.processor.TransformerFactoryImpl() 
+10
source

Here is the solution for completeness:

 System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI, "org.apache.xpath.jaxp.XPathFactoryImpl"); System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl"); XPathFactory jaxpFactory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI); XPathFactory saxonFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); 
+2
source

Source: https://habr.com/ru/post/919123/


All Articles