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>
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();
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);
To use XSLTC, put xalan.jar(2.5), serializer.jar, xml-apis.jar, and xercesImpl.jar on your classpath .
精彩评论