How to transform XML with XSL using Java

23,923

Solution 1

I came across a post on the net that mentioned apache XALAN. So I added the jars to my project. Everything has started working since even though I do not directly reference any XALAN classes in my code. As far as I can tell it still should use the jaxax.xml classes.

Not too sure what is happening there. But it is working.

Solution 2

Try Saxon instead.

Your code would stay the same. All you would need to do is set javax.xml.transform.TransformerFactory to net.sf.saxon.TransformerFactoryImpl in the JVM's system properties.

Solution 3

Use saxon. offtop: if you use the same stylesheet to transform many XML files, you might want to consider templates (pre-compiled stylesheets):

javax.xml.transform.Templates style = tFactory.newTemplates(xslSource);
style.newTransformer().transform(...);
Share:
23,923
Andez
Author by

Andez

Updated on August 02, 2020

Comments

  • Andez
    Andez almost 4 years

    I am currently using the standard javax.xml.transform library to transform my XML to CSV using XSL. My XSL file is large - at around 950 lines. My XML files can be quite large also.

    It was working fine in the prototype stage with a fraction of the XSL in place at around 50 lines or so. Now in the 'final system' when it performs the transform it comes up with the error Branch target offset too large for short.

    private String transformXML() {
        String formattedOutput = "";
        try {
    
            TransformerFactory tFactory = TransformerFactory.newInstance();            
            Transformer transformer =
                    tFactory.newTransformer( new StreamSource( xslFilename ) );
    
            StreamSource xmlSource = new StreamSource(new ByteArrayInputStream( xmlString.getBytes() ) );
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            transformer.transform( xmlSource, new StreamResult( baos ) );
    
            formattedOutput = baos.toString();
    
        } catch( Exception e ) {
            e.printStackTrace();
        }
    
        return formattedOutput;
    }
    

    I came across a few postings on this error but not too sure what to do.
    Am I doing anything wrong code wise? Are there any alternative 3rd Party transformers available that could do this?

    Thanks,

    Andez