我想用Java中的XSLT转换XML。为此我正在使用javax.xml.transform
包。但是,我得到例外javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
。这是我正在使用的代码:
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();
}
请注意,我标记了引发异常的行。
当我输入方法时,XSLTRule
的值为:
<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>
答案 0 :(得分:9)
public StreamSource(String systemId)
从URL构造StreamSource。我认为你正在传递XSLT的内容。试试这个:
File xslFile = new File("path/to/your/xslt");
TransformerFactory factory = TransformerFactory.newInstance();
Templates xsl = factory.newTemplates(new StreamSource(xslFile));
您还必须设置OutputStream
将写入的StreamResult
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
return baos.toString();
答案 1 :(得分:1)
您必须从您拥有的xslt字符串构造一个流,然后将其用作流源
InputStream xslStream = new ByteArrayInputStream(XSLTRule.getBytes("UTF-8"));
Source xslInput = new StreamSource(xslStream);
要将结果转换为字符串:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Result result = new StreamResult(bos);
transformer.transform(xmlInput, result);
String s = new String(bos.toByteArray());
System.out.println(s);
答案 2 :(得分:0)
要使用XSLTC,请在类路径中输入xalan.jar(2.5),serializer.jar,xml-apis.jar和xercesImpl.jar。