当前位置:  开发笔记 > 编程语言 > 正文

由于xsl:include导致转换失败

如何解决《由于xsl:include导致转换失败》经验,为你挑选了2个好方法。

我有一个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);

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

XSLT中的include语句是相对链接

xsl:include href="footer.xsl"
xsl:include href="topbar.xsl"

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

xsl:include href="xsl/footer.xsl"
xsl:include href="xsl/topbar.xsl"

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



1> will..:

使用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 (...

并使用TransformerFactory进行分配

tFactory.setURIResolver(new MyURIResolver());



2> 小智..:

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;
        }
    }
}

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

TransformerFactory transFact = TransformerFactory.newInstance();
transFact.setURIResolver(new XsltURIResolver());

或者使用lambda表达式:

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

推荐阅读
Gbom2402851125
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有