The XUnparsedTextResolver interface can be implemented and the implementation registered with the XDynamicContext to override the default resolution behavior for resources loaded through the XSLT unparsed-text function.
The default resolution behavior for resources loaded through the XSLT unparsed-text function is to resolve relative URIs based on the base URI from the static context. If the base URI is not available, the current working directory is used. Absolute URIs are used unchanged.
XFactory factory = XFactory.newInstance(); // Prepare the stylesheet. XSLTExecutable executable = factory.prepareXSLT(new StreamSource(stylesheetFile)); // Create the dynamic context and set the unparsed text resolver. XDynamicContext dynamicContext = factory.newDynamicContext(); AnUnparsedTextResolver resolver = new AnUnparsedTextResolver(replacementBase); dynamicContext.setUnparsedTextResolver(resolver); // Execute the transformation. Source source = new StreamSource(inputFile); Result result = new StreamResult(System.out); executable.execute(source, dynamicContext, result);
class AnUnparsedTextResolver implements XUnparsedTextResolver { String _replacementBase; public AnUnparsedTextResolver(String replacementBase) { _replacementBase=replacementBase; } // Resolve URI, returning the resource that URI represents. // Implements the "rebase:" pseudo-scheme. public String getResource(String href, String encoding, String base) { String rebasePrefix="rebase:"; if (href.startsWith(rebasePrefix)) { href = href.substring(rebasePrefix.length()); base = _replacementBase; } try { // Get base URI object URI uri = new java.net.URI(base); // Resolved relative reference against base URI URI resolvedURI = uri.resolve(href); // Try to read... URL url = resolvedURI.toURL(); URLConnection urlCon = url.openConnection(); BufferedInputStream stream = new BufferedInputStream(urlCon.getInputStream()); StringBuffer buffer = new StringBuffer(); int s; while ((s = stream.read())!= -1) { // Do any character manipulation here. buffer.append((char)s); } return buffer.toString(); } catch (Exception e) { throw new RuntimeException(e); } } }