我想用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();
}
Run Code Online (Sandbox Code Playgroud)
请注意,我标记了抛出异常的行.
当我输入方法时,值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>
Run Code Online (Sandbox Code Playgroud)
Mar*_*coS 10
该构造
public StreamSource(String systemId)
Run Code Online (Sandbox Code Playgroud)
从URL构造StreamSource.我认为你正在传递XSLT的内容.试试这个:
File xslFile = new File("path/to/your/xslt");
TransformerFactory factory = TransformerFactory.newInstance();
Templates xsl = factory.newTemplates(new StreamSource(xslFile));
Run Code Online (Sandbox Code Playgroud)
您还必须设置OutputStream您StreamResult要写入的内容:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
return baos.toString();
Run Code Online (Sandbox Code Playgroud)