Java使用Saxon-HE 10.5做XSLT3转换时xsl:import的href文件找不到如何解决
Saxon-HE XSLT导入资源路径问题解决方案
问题背景
我正在开发一款Java应用,采用Maven项目架构引入Saxon-HE 10.5依赖,基于XSLT3实现XML转换功能。
我的主XSLT样式表通过<xsl:import>导入其他XSLT文件(示例写法:<xsl:import href="sheet1.xsl"/>),所有XSLT文件均存放于项目的./src/main/resources目录下。但程序运行时Saxon抛出FileNotFound异常,经排查发现Saxon默认在项目根目录查找导入的XSLT文件。
我希望调整Saxon查找导入文件的路径,但未找到基于s9api接口的实现方案,最初的转换代码如下:
public void transformXML(String xmlFile, String output) throws SaxonApiException, IOException, XPathExpressionException, ParserConfigurationException, SAXException { Processor processor = new Processor(false); XsltCompiler compiler = processor.newXsltCompiler(); XsltExecutable stylesheet = compiler.compile(new StreamSource(this.getClass().getClassLoader().getResourceAsStream("transform.xsl"))); Serializer out = processor.newSerializer(new File(output)); out.setOutputProperty(Serializer.Property.METHOD, "text"); Xslt30Transformer transformer = stylesheet.load30(); transformer.transform(new StreamSource(new File(xmlFile)), out); }
可用解决方案
通过为XsltCompiler设置自定义的URIResolver,实现从类路径读取导入的XSLT资源,最终实现代码如下:
public void transformXML(String xmlFile, String output) throws SaxonApiException, IOException, XPathExpressionException, ParserConfigurationException, SAXException { Processor processor = new Processor(false); XsltCompiler compiler = processor.newXsltCompiler(); compiler.setURIResolver(new ClasspathResourceURIResolver()); XsltExecutable stylesheet = compiler.compile(new StreamSource(this.getClass().getClassLoader().getResourceAsStream("transform.xsl"))); Serializer out = processor.newSerializer(new File(output)); out.setOutputProperty(Serializer.Property.METHOD, "text"); Xslt30Transformer transformer = stylesheet.load30(); transformer.transform(new StreamSource(new File(xmlFile)), out); } } class ClasspathResourceURIResolver implements URIResolver { @Override public Source resolve(String href, String base) throws TransformerException { return new StreamSource(this.getClass().getClassLoader().getResourceAsStream(href)); } }
内容的提问来源于stack exchange,提问作者DerMannMitDerMaske
相关产品推荐
相关产品推荐

