我需要使用 Apache FOP 进行 XSL 转换,我的代码如下:
//Setup FOP
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
//Setup Transformer
Source xsltSrc = new StreamSource(new File(xslPath));
Transformer transformer = tFactory.newTransformer(xsltSrc);
//Make sure the XSL transformation's result is piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
//Setup input
Source src = new StreamSource(new File(xmlPath));
//Start the transformation and rendering process
transformer.transform(src, res);
where xslPath
是我的 XSLT 文件的存储路径。
我已经确认当我只有一个 XSLT 文件时它可以工作,但在我的项目中我已将内容分成几个 XSLT 文件并将它们与<xsl:import />
标签。使用此配置,我收到 NullPointerException,因为它无法理解存储在 XSLT 中的所有信息,因为它分布在不同的文件中。
我想知道是否有任何方法可以加载所有这些文件Source xsltSrc
变量,因此所有 XSL 信息都可用。
UPDATE
我已经根据 Mads Hansen 给出的答案更改了代码,但它仍然不起作用。我必须将 XSLT slt 文件包含在类路径中,因此我使用 ClassLoader 加载 XSLT 文件。我检查了执行时 URL 的路径是否正确url.toExternalForm()
。这是我的新代码:
ClassLoader cl = this.getClass().getClassLoader();
String systemID = "resources/xslt/myfile.xslt";
InputStream in = cl.getResourceAsStream(systemID);
URL url = cl.getResource(systemID);
Source source = new StreamSource(in);
source.setSystemId(url.toExternalForm());
transformer = tFactory.newTransformer(source);
它找到并加载myfile.xslt
但它仍然无法解析其他 XSLT 文件的相对路径。
我究竟做错了什么?