Java Transformer error: Could not compile styleshe

2019-02-13 06:59发布

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>

标签: java xml xslt
3条回答
手持菜刀,她持情操
2楼-- · 2019-02-13 07:04

To use XSLTC, put xalan.jar(2.5), serializer.jar, xml-apis.jar, and xercesImpl.jar on your classpath .

查看更多
Emotional °昔
3楼-- · 2019-02-13 07:11

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();
查看更多
做自己的国王
4楼-- · 2019-02-13 07:13

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);
查看更多
登录 后发表回答