Java Transformer错误:无法编译样式表
我想用Java中的XSLT转换XML。 为此,我使用的是javax.xml.transform
包。 但是,我得到了exceptionjavax.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(); }
请注意,我标记了抛出exception的行。
当我输入方法时, XSLTRule
的值是这样的:
构造函数
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();
您必须从您拥有的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);
要使用XSLTC,请在类路径中放置xalan.jar(2.5),serializer.jar,xml-apis.jar和xercesImpl.jar。