我想用 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>
最佳答案
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));
您还必须设置您的 StreamResult
将写入的 OutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
return baos.toString();
关于Java 转换器错误 : Could not compile stylesheet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5472298/