由于xsl:include导致转换失败

wil*_*ill 7 java xslt

我有一个Java maven项目,其中包括XSLT转换.我加载样式表如下:

TransformerFactory tFactory = TransformerFactory.newInstance();

DocumentBuilderFactory dFactory = DocumentBuilderFactory
                .newInstance();

dFactory.setNamespaceAware(true);

DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("xsl/stylesheet.xsl");

InputSource xslInputSource = new InputSource(in);
Document xslDoc = dBuilder.parse(xslInputSource);

DOMSource xslDomSource = new DOMSource(xslDoc);

Transformer transformer = tFactory.newTransformer(xslDomSource);
Run Code Online (Sandbox Code Playgroud)

stylesheet.xsl有许多语句.这些似乎导致问题,当我尝试运行我的单元测试时,我收到以下错误:

C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: footer.xsl
C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: topbar.xsl
Run Code Online (Sandbox Code Playgroud)

XSLT中的include语句是相对链接

xsl:include href="footer.xsl"
xsl:include href="topbar.xsl"
Run Code Online (Sandbox Code Playgroud)

我尝试过尝试并将这些更改为以下内容 - 但我仍然得到错误.

xsl:include href="xsl/footer.xsl"
xsl:include href="xsl/topbar.xsl"
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?任何帮助非常感谢.

wil*_*ill 12

使用URIResolver解决了我的问题.

class MyURIResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
  try {
    ClassLoader cl = this.getClass().getClassLoader();
    java.io.InputStream in = cl.getResourceAsStream("xsl/" + href);
    InputSource xslInputSource = new InputSource(in);
    Document xslDoc = dBuilder.parse(xslInputSource);
    DOMSource xslDomSource = new DOMSource(xslDoc);
    xslDomSource.setSystemId("xsl/" + href);
    return xslDomSource;
 } catch (...
Run Code Online (Sandbox Code Playgroud)

并使用TransformerFactory进行分配

tFactory.setURIResolver(new MyURIResolver());
Run Code Online (Sandbox Code Playgroud)


小智 9

URIResolver也可以更直接的方式使用,如下所示:

class XsltURIResolver implements URIResolver {

    @Override
    public Source resolve(String href, String base) throws TransformerException {
        try{
              InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("xslts/" + href);
              return new StreamSource(inputStream);
        }
        catch(Exception ex){
            ex.printStackTrace();
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将URIResolver与TransformerFactory一起使用,如下所示:

TransformerFactory transFact = TransformerFactory.newInstance();
transFact.setURIResolver(new XsltURIResolver());
Run Code Online (Sandbox Code Playgroud)

或者使用lambda表达式:

transFact.setURIResolver((href, base) -> {
    final InputStream s = this.getClass().getClassLoader().getResourceAsStream("xslts/" + href);
    return new StreamSource(s);
});
Run Code Online (Sandbox Code Playgroud)