Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform XML with XSL using Java

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

like image 368
Andez Avatar asked Apr 18 '26 02:04

Andez


2 Answers

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.

like image 196
dogbane Avatar answered Apr 19 '26 23:04

dogbane


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(...);
like image 25
khachik Avatar answered Apr 20 '26 00:04

khachik