Java – parsing relative paths when loading XSLT files
I need to use Apache FOP for XSL transformation. I have the following code:
//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 is the path where my XSLT file is stored
I have confirmed that it works when I have only one XSLT file, but in my project, I divide things into several XSLT files and label them with < xsl: import / > With this configuration, I get a NullPointerException because it cannot understand all the information stored in XSLT because it is distributed on different files
I wonder if there is any way to load all these files in the source xsltsrc variable so that all XSL information is available
UPDATE
I've changed the code based on MADS Hansen's answer, but it still doesn't work I have to include XSLT SLT files in the classpath, so I use classloader to load XSLT files Execute URL To externalform(), I have checked whether the path of the URL is correct This is my new code:
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);
It finds and loads myfile XSLT, but still unable to parse the relative path to other XSLT files
What on earth did I do wrong?
Solution
I just got it, a late answer (tested in FOP 1.0)——
What you need is to set up a URI parser for your factory, as shown below:
TransformerFactory transFact = TransformerFactory.newInstance(); StreamSource xsltSource = new StreamSource(xsl); // XXX for 'xsl:import' to load other xsls from class path transFact.setURIResolver(new ClassPathResourceURIResolver()); Templates cachedXSLT = transFact.newTemplates(xsltSource); Transformer transformer = cachedXSLT.newTransformer(); class ClassPathResourceURIResolver implements URIResolver { @Override public Source resolve(String href,String base) throws TransformerException { return new StreamSource(XXX.getClassLoader().getResourceAsStream(href)); } }
And the XSL I imported (so 'imported. XSL' should be in the classpath):
<xsl:import href="Meta-INF/companybusinesscredit/imported.xsl"/>