Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Transformer error: Could not compile stylesheet

Tags:

java

xml

xslt

I'm want to transform a XML with XSLT in Java. For that I'm using the javax.xml.transform package. However, I get the exception javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet. This is the code I'm using:

public static String transform(String XML, String XSLTRule) throws TransformerException {

    Source xmlInput = new StreamSource(XML);
    Source xslInput = new StreamSource(XSLTRule);

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xslInput); // this is the line that throws the exception

    Result result = new StreamResult();
    transformer.transform(xmlInput, result);

    return result.toString();
}

Note that I marked the line which throws the exception.

When I enter the method, the value of XSLTRule is this:

<xsl:stylesheet version='1.0'
 xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
 xmlns:msxsl='urn:schemas-microsoft-com:xslt'
 exclude-result-prefixes='msxsl'
 xmlns:ns='http://www.ibm.com/wsla'>
    <xsl:strip-space elements='*'/>
    <xsl:output method='xml' indent='yes'/>
    <xsl:template match='@* | node()'>
        <xsl:copy>
            <xsl:apply-templates select='@* | node()'/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="/ns:SLA
                            /ns:ServiceDefinition
                               /ns:WSDLSOAPOperation
                                  /ns:SLAParameter[@name='Performance']"/>
</xsl:stylesheet>
like image 877
Ivan Avatar asked Mar 29 '11 12:03

Ivan


2 Answers

The constructor

public StreamSource(String systemId)

Construct a StreamSource from a URL. I think you're passing the content of the XSLT instead. Try this:

File xslFile = new File("path/to/your/xslt");
TransformerFactory factory = TransformerFactory.newInstance();
Templates xsl = factory.newTemplates(new StreamSource(xslFile));

You must also set the OutputStream that your StreamResult will write to:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
return baos.toString();
like image 93
MarcoS Avatar answered Nov 04 '22 17:11

MarcoS


You will have to contruct a stream from the xslt string you have and then use it as the stream source

InputStream xslStream = new ByteArrayInputStream(XSLTRule.getBytes("UTF-8"));
Source xslInput = new StreamSource(xslStream);

To get the result to a string :

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Result result = new StreamResult(bos);
    transformer.transform(xmlInput, result);
    String s = new String(bos.toByteArray());
    System.out.println(s);
like image 44
Nishan Avatar answered Nov 04 '22 15:11

Nishan