Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force use of specific XML parser

Tags:

java

parsing

xml

I have Xerces and Oracle XML parsers both in my application's classpath (don't ask why).

When I create a new javax.xml.parsers.DocumentBuilderFactory, the classloader automatically picks up the Oracle XML parser. However, it's not a full/proper implementation, so it's giving me headaches.

Is there a way I can force/tell the classloader to use the Xerces parces when constructing the document builder factory?

like image 696
dasp Avatar asked Feb 26 '23 14:02

dasp


2 Answers

For my large project, skaffman's answer would have worked MOST of the time, but not ALL of the time because we have multiple sub-projects that depend on these libraries. We looked at the source to javax.xml.transform.TransformerFactory.newInstance(), and found that it uses javax.xml.transform.FactoryFinder.find("javax.xml.transform.TransformerFactory", ...). This method then looks at a system parameter to determine the correct implementation.

We ultimately fixed it by adding -D parameters to our runtime to force the correct classes:

-Djavax.xml.transform.TransformerFactory=org.apache.xalan.processor.TransformerFactoryImpl -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl

like image 85
KJP Avatar answered Mar 08 '23 02:03

KJP


DocumentBuilderFactory has a newInstance() method where you can specify the class name of the implementation you want to use.

like image 29
skaffman Avatar answered Mar 08 '23 00:03

skaffman