I use quiet a lot XSL transformations at work. Since they tend to grow rather big with every new rule I implement, I split the file up. Every file has it’s own domain/rule. This works fine. I also write a new junit test for every new xslt rule/template, to ensure that I did not break anything.

At somepoint in every new project I get the error, that a transformation in production (src/main) does work, but in test (src/test) does not. After a few minutes of searching I come to the conclusion, that a import/include stylesheet can not be found. A few minutes later and the penny dropes… I always forget to implement the URIResolver. Every time…

import java.io.InputStream;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;


public class XsltURIResolver implements URIResolver {


    @Override
    public Source resolve(String href, String base) throws TransformerException {
        try {
            final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(href);
            return new StreamSource(inputStream);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

And they setting it:

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