Search code examples
javaxmljava-7java-6

How to use java internal XMLStreamWriter with another provider present


I'm using this code to get an XMLStreamWriter:

javax.xml.stream.XMLOutputFactory
    .newInstance()
    .createXMLStreamWriter( outputStream )

Recently I had to include the jars of jaxws to my system. After that the XmlStreamWriter implementation changed from com.sun.xml.internal.stream.writers.XMLStreamWriterImpl to com.ctc.wstx.sw.SimpleNsStreamWriter. This class produces a different output than the java internal implementation.

How can I force java to use the internal implementation without binding my code to java 6 by using com.sun.xml.internal.stream.XMLOutputFactoryImpl explicitly? Java 7 uses a different XMLStreamWriter, and I want my code to run with java 7, too.


I tried this:

XMLOutputFactory.newFactory( 
    "com.sun.xml.internal.stream.XMLOutputFactoryImpl", 
    getClass().getClassLoader() 
);

which is working with Oracle JDK 6, but with JDK 7 it leads to

javax.xml.stream.FactoryConfigurationError: 
Provider for com.sun.xml.internal.stream.XMLOutputFactoryImpl cannot be found  

Solution

  • According to the javadoc this is how the factory operates:

    • Use the javax.xml.stream.XMLOutputFactory system property.
    • Use the properties file "lib/stax.properties" in the JRE directory.
    • Use the Services API (as detailed in the JAR specification)
    • Platform default XMLOutputFactory instance.

    So to be sure to use the sun internal implementation, I think the best way is to do the following:

    System.setProperty("javax.xml.stream.XMLOutputFactory", "com.sun.xml.internal.stream.XMLOutputFactoryImpl");
    XMLOutputFactory.newInstance();