Java Code Examples for javax.xml.transform.TransformerFactory

Following code examples demonstrate how to use javax.xml.transform.TransformerFactoryfrom java. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use javax.xml.transform.TransformerFactoryand various code implementation of this class.

    @PostConstruct
    public void initialize()
    {
        Logger.getLogger(Transformer.class.getName()).log(Level.FINER, "Initialize Called");
        if (xsltStyleSheet == null)
        {
            Logger.getLogger(Transformer.class.getName()).log(Level.SEVERE, "xsltStyleSheet resource is not defined");
        }
        else
        {

            String txFact = System.getProperty("javax.xml.transform.TransformerFactory");


            try
            {
                System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");

                TransformerFactory tfactory = TransformerFactory.newInstance();
                tx = tfactory.newTransformer(new StreamSource(xsltStyleSheet.getInputStream()));
                if (tx != null)
                {
                    if (styleSheetParameters != null)
                    {
                        Iterator<String> keyItr = styleSheetParameters.keySet().iterator();
                        while (keyItr.hasNext())
                        {
                            String key = keyItr.next();
                            tx.setParameter(key, styleSheetParameters.get(key));
                        }
                    }
                }
                else
                {
                    Logger.getLogger(Transformer.class.getName()).log(Level.SEVERE, "Unable to load {0}", xsltStyleSheet.getFilename());
                    
                }
            }
            catch (IOException ex)
            {
                Logger.getLogger(Transformer.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch (TransformerConfigurationException ex)
            {
                Logger.getLogger(XSLTTransformStep.class.getName()).log(Level.SEVERE, null, ex);
            }
            finally
            {
                if (txFact == null)
                {
                    System.clearProperty("javax.xml.transform.TransformerFactory");
                }
                else
                {
                    System.setProperty("javax.xml.transform.TransformerFactory", txFact);
                }

            }
        }

    } 


	public String xsltTransform(String xmlFile, String xsltFile) throws Exception{
		
		
        javax.xml.transform.TransformerFactory trans = javax.xml.transform.TransformerFactory.newInstance();
        javax.xml.transform.Transformer xformer = trans.newTransformer(styleSource);
        Writer outWriter = new StringWriter();
        xformer.transform(new StreamSource( new StringReader(xmlFile)), new StreamResult(outWriter));
        return outWriter.toString();
        
	} 

	public void testSaxon0() throws Exception {

	    System.setProperty("javax.xml.transform.TransformerFactory",
	            "net.sf.saxon.TransformerFactoryImpl");
	    File xml_file = Fixtures.F507405_XML;
	    File xsl_file = Fixtures.MINI_XSL;
	    

	    TransformerFactory tfactory = TransformerFactory.newInstance();
	    Transformer transformer = tfactory.newTransformer(new StreamSource(xsl_file));
	    transformer.transform(new StreamSource(xml_file), new StreamResult(System.out));
	} 

	public void testChain() throws Exception {
		SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)TransformerFactory.newInstance();

		Templates templates1 = saxTransformerFactory.newTemplates(new StreamSource(
		  getClass().getResourceAsStream("MyStylesheet1.xslt")));
		Templates templates2 = saxTransformerFactory.newTemplates(new StreamSource(
		  getClass().getResourceAsStream("MyStylesheet1.xslt")));

		TransformerHandler transformerHandler1 = saxTransformerFactory.newTransformerHandler(templates1);
		TransformerHandler transformerHandler2 = saxTransformerFactory.newTransformerHandler(templates2);

		transformerHandler1.setResult(new SAXResult(transformerHandler2));
		transformerHandler2.setResult(new StreamResult(System.out));

		Transformer transformer = saxTransformerFactory.newTransformer();
		SAXResult saxResult1 = new SAXResult(transformerHandler1);
		transformer.transform(new StreamSource(System.in), saxResult1);

	} 

	public void test() {
		
		
		 * 
		 * 

    Explicitly instantiate the Saxon factory (with a nod to Michael's comment above):

    TransformerFactory fact = new net.sf.saxon.TransformerFactoryImpl()

    Specify the factory class when constructing it:

    TransformerFactory fact = TransformerFactory.newInstance(
            "net.sf.saxon.TransformerFactoryImpl", null);

    (Note: available as of Java 6. The Java 5 version does not have this method.)

    Set the javax.xml.transform.TransformerFactory system property before creating an instance:

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

    Or on the command line (line broken for readability):

    java -Djavax.xml.transform.TransformerFactory=
            cnet.sf.saxon.TransformerFactoryImpl YourApp

    Create the following file:

    JRE/lib/jaxp.properties

    With the following contents:

    javax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl

    Create the following file in any JAR on the CLASSPATH:

    META-INF/services/javax.xml.transform.TransformerFactory

    With the following contents:

    net.sf.saxon.TransformerFactoryImpl 

    If none of the above are done, then the platform default TransformerFactory instance will be loaded

A friendly description of this plugability layer can be found here:


I'd consider this answer an argument against the Java way of doing things.
		 */
	} 

	public void testSaxonXslt2GroupTest1() throws Exception {

	    File xml_file = Fixtures.XSLT2_TEST1_XML;
	    File xsl_file = Fixtures.XSLT2_TEST1_XSL;
	    

	    System.setProperty("javax.xml.transform.TransformerFactory",
	            "net.sf.saxon.TransformerFactoryImpl");
	    TransformerFactory tfactory = TransformerFactory.newInstance();
	    Transformer transformer = tfactory.newTransformer(new StreamSource(xsl_file));
	    File saxonDir = new File("target/saxon/");
	    saxonDir.mkdirs();
    	transformer.transform(new StreamSource(xml_file),  
    		new StreamResult(new FileOutputStream(new File(saxonDir, "test1.xml"))));
	} 

    public static void init(String implementationName) {
    	debug("Implementation name: " + implementationName);
        if(implementationName != null && implementationName.length() > 0) {
            factory = TransformerFactory.newInstance(implementationName, null);
        } else {
            factory = TransformerFactory.newInstance();
        }
    } 

    @Test
    public default void verifyGenericType()
    throws Exception {
        final Class<SUT> sut = createNewSUT();
        assertTrue("This j8unit test interface is used with a generic type that is illegaly not assignable to TransformerFactory.class!",
                   TransformerFactory.class.isAssignableFrom(sut));
    } 

    @Override public TransformerFactory get() {
        try {
            if (factoryClass == null) {
                return TransformerFactory.newInstance();
            } else {
                return TransformerFactory.newInstance(factoryClass, null);
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not create a transformer factory, check your "
                                       + "javax.xml.transform.TransformerFactory setting.", e);
        }
    } 

	public void releaseBroker(DBBroker broker) throws EXistException {
		if (pool == null)
			throw new EXistException("Database wan't set properly.");

		pool.release(broker);
	} 

	public static void transform(File xmlfile, File xslfile, File outfile, String version) throws FileNotFoundException, TransformerException{ 
		TransformerFactory factory = null; 
		
		if(XSLT_VERSION_1.equals(version)){
			factory = TransformerFactory.newInstance();
		}else if(XSLT_VERSION_2.equals(version)){
			factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null);			
		}else{
			System.err.println("Unsupported version '"+version+"', use processor 1.0.");
			factory = TransformerFactory.newInstance();
		}
		
		Templates template = factory.newTemplates(new StreamSource( 
				new FileInputStream(xslfile))); 
		
		Transformer xformer = template.newTransformer(); 
		
		Source source = new StreamSource(new FileInputStream(xmlfile)); 
		Result result = new StreamResult(new FileOutputStream(outfile)); 
		
		xformer.transform(source, result);
	} 

    public static void main(String[] args) throws TransformerException {

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

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer(new StreamSource(new File("XML/XSLT/XSLT-1-Simple/resources/simple.xsl")));

        System.out.println("Transformer: " + transformer.getClass().getCanonicalName());

        transformer.transform(new StreamSource(new File("XML/XSLT/XSLT-1-Simple/resources/data.xml")), new StreamResult(System.out));

    } 

    public String transform(StreamSource streamSourceInput, String param, Object value) throws Exception {

        StringWriter out = new StringWriter();

        javax.xml.transform.TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance( );
        javax.xml.transform.Transformer trans = transFact.newTransformer(styleSheet);
        trans.setParameter(param, value);

        trans.transform(streamSourceInput, new StreamResult(out));

        return out.toString();
    } 

    public String transform(StreamSource streamSourceInput) throws Exception {

        StringWriter out = new StringWriter();

        javax.xml.transform.TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance( );
        javax.xml.transform.Transformer trans = transFact.newTransformer(styleSheet);

        trans.transform(streamSourceInput, new StreamResult(out));
        

        return out.toString();
    } 

  public static String xsltTransform(StreamSource xslStream, StreamSource xmlStream) {
    
    StringWriter sw = new StringWriter();
    
    
    
    try {
      
      javax.xml.transform.TransformerFactory xformFactory =
          javax.xml.transform.TransformerFactory.newInstance();
      
      Transformer transformer = xformFactory.newTransformer(xslStream);
      
      transformer.transform(xmlStream, new StreamResult(sw));
    } catch (Exception er) {
      LOGGER.log(Level.SEVERE,er.getMessage());
    }
    
    return sw.toString();
  } 

  }

  public static Node doTransform(InputStream originalXml, String transformLocation)
  {
    System.out.println("javax.xml.transform.TransformerFactory = " + System.getProperty("javax.xml.transform.TransformerFactory"));

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    DOMResult result = new DOMResult();
    try {
      Source xmlSource = new StreamSource(originalXml);
      Source xsltSource = new StreamSource(transformLocation);

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer(xsltSource);
      transformer.transform(xmlSource, result);
    } catch (TransformerConfigurationException tce) {
      tce.printStackTrace();
      return null;
    } catch (TransformerException te) {
      te.printStackTrace();
      return null;
    }

    System.clearProperty("javax.xml.transform.TransformerFactory");
    return result.getNode();
  } 

  public static String doTransform(Document originalXml, Node transform) {
    System.out.println("javax.xml.transform.TransformerFactory = " + System.getProperty("javax.xml.transform.TransformerFactory"));

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    StreamResult result = new StreamResult(os);
    try {
      Source xmlSource = new DOMSource(originalXml);
      Source xsltSource = new DOMSource(transform);

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer(xsltSource);
      transformer.transform(xmlSource, result);
    } catch (TransformerConfigurationException tce) {
      tce.printStackTrace();
      return null;
    } catch (TransformerException te) {
      te.printStackTrace();
      return null;
    }
    System.clearProperty("javax.xml.transform.TransformerFactory");

    return os.toString();
  } 

  }

  public static Node doTransform(InputStream originalXml, InputStream transform, String phase)
  {
    System.out.println("javax.xml.transform.TransformerFactory = " + System.getProperty("javax.xml.transform.TransformerFactory"));

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    DOMResult result = new DOMResult();
    try {
      Source xmlSource = new StreamSource(originalXml);
      Source xsltSource = new StreamSource(transform);

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer(xsltSource);
      transformer.setParameter("phase", phase);
      transformer.transform(xmlSource, result);
    } catch (TransformerConfigurationException tce) {
      tce.printStackTrace();
      return null;
    } catch (TransformerException te) {
      te.printStackTrace();
      return null;
    }
    System.clearProperty("javax.xml.transform.TransformerFactory");
    return result.getNode();
  } 

  }

  public static String doTransform(InputStream originalXml, Node transform)
  {
    System.out.println("javax.xml.transform.TransformerFactory = " + System.getProperty("javax.xml.transform.TransformerFactory"));

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    StreamResult result = new StreamResult(os);
    try {
      Source xmlSource = new StreamSource(originalXml);
      Source xsltSource = new DOMSource(transform);

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer(xsltSource);
      transformer.transform(xmlSource, result);
    } catch (TransformerConfigurationException tce) {
      tce.printStackTrace();
      return null;
    } catch (TransformerException te) {
      te.printStackTrace();
      return null;
    }
    System.clearProperty("javax.xml.transform.TransformerFactory");

    return os.toString();
  } 

    
    private static void generateController() throws TransformerConfigurationException, TransformerException
    {
        System.setProperty
        (
            "javax.xml.transform.TransformerFactory",
            "net.sf.saxon.TransformerFactoryImpl"
        );
        TransformerFactory
            .newInstance()
            .newTransformer(
                    .transform(
    } 

    
    private static void generateOrm() throws TransformerConfigurationException, TransformerException
    {
        System.setProperty
        (
            "javax.xml.transform.TransformerFactory",
            "net.sf.saxon.TransformerFactoryImpl"
        );
        TransformerFactory
            .newInstance()
            .newTransformer(
                    .transform(
    } 

    
    private static void generateGui() throws TransformerConfigurationException, TransformerException
    {
        System.setProperty
        (
            "javax.xml.transform.TransformerFactory",
            "net.sf.saxon.TransformerFactoryImpl"
        );
        TransformerFactory
            .newInstance()
            .newTransformer(
                    .transform(
    } 

    
    private static void combineBPIWithGUI() throws TransformerConfigurationException, TransformerException
    {
        System.setProperty
        (
            "javax.xml.transform.TransformerFactory",
            "net.sf.saxon.TransformerFactoryImpl"
        );
        TransformerFactory
            .newInstance()
            .newTransformer(
                    .transform(
    } 

    
    private static void generateHibernateConfiguration() throws TransformerConfigurationException, TransformerException
    {
        System.setProperty
        (
            "javax.xml.transform.TransformerFactory",
            "net.sf.saxon.TransformerFactoryImpl"
        );
        TransformerFactory
            .newInstance()
            .newTransformer(
                    .transform(
    } 

    
    private static void generateMainMethod() throws TransformerConfigurationException, TransformerException
    {
        System.setProperty
        (
            "javax.xml.transform.TransformerFactory",
            "net.sf.saxon.TransformerFactoryImpl"
        );
        TransformerFactory
            .newInstance()
            .newTransformer(
                    .transform(
    } 

    
    private static void generateJavaModel() throws TransformerConfigurationException, TransformerException
    {
        System.setProperty
        (
            "javax.xml.transform.TransformerFactory",
            "net.sf.saxon.TransformerFactoryImpl"
        );
        TransformerFactory
            .newInstance()
            .newTransformer(
                    .transform(
    } 

Advertisement
Javadoc


A TransformerFactory instance can be used to create javax.xml.transform.Transformer and ja

vax.xml.transform.Templates objects.

The system property that determines which Factory implementation to create is named "javax.xml.transform.TransformerFactory". This property names a concrete subclass of the TransformerFactory abstract class. If the property is not defined, a platform default is be used. @author Jeff Suttor

Read More
Advertisement