执行时使用结果解析器
通过在执行时指定结果解析器,您可以告知处理器如何重定向可执行文件中指定的输出 URI。
过程
要激活结果解析器,请先向动态上下文注册此解析器,然后调用 execute()。
结果解析器执行的功能与源解析器执行的功能基本相同,但只是从处理器的输出方面而言。它们允许您拦截和重定向可执行文件中指定的输出 URI,如样式表中的 xsl:result-documen 伪指令。
缺省解析行为是使用基本输出 URI,以在 URI 引用为相对引用的情况下解析结果文档。使用绝对 URI 保持不变。
以下是结果解析器的基本示例。
class AResultResolver implements XResultResolver
{
String _replacementBase;
public AResultResolver(String replacementBase)
{
_replacementBase=replacementBase;
}
// Resolve URIs by loading the resource as an XSLT stylesheet
// and evaluating it - return the result as the Source to use
public Result getResult(String href, String base) {
String rebasePrefix="rebase://";
if(href.startsWith(rebasePrefix))
{
href=href.substring(rebasePrefix.length());
base=_replacementBase;
}
java.net.URI baseURI;
Result result=null;
try {
// Get base URI object
baseURI = new java.net.URI(base);
// Resolved relative reference against base URI
URI resolvedURI = baseURI.resolve(href);
// Try to read...
result = new StreamResult(resolvedURI.toString());
} catch (java.net.URISyntaxException use) {
throw new RuntimeException(use);
}
return result;
}
}
以下是注册和使用解析器的基本示例。
XFactory factory = XFactory.newInstance();
XStaticContext staticContext = factory.newStaticContext();
// Prepare the stylesheet
XSLTExecutable executable = factory.prepareXSLT(new StreamSource(stylesheetFile), staticContext);
XDynamicContext dynamicContext = factory.newDynamicContext();
// Register the result resolver with the dynamic context
XResultResolver resultResolver=new AResultResolver(replacementBase);
dynamicContext.setResultResolver(resultResolver);
// Execute the XPath expression
XSequenceCursor cursor = executable.execute(new StreamSource(inputFile), dynamicContext);