使用模块解析器
可以实现 XModuleResolver 接口,且向 XStaticContext 注册实现以覆盖缺省 XQuery 模块解析行为。不管何时遇到 XQuery 模块导入,都将解析模块。
关于此任务
缺省模块解析行为是尝试定位一个模块,以找到模块导入中指定的每个位置提示。每个位置提示的缺省解析行为是在基本 URI 可用的情况下,根据静态上下文中的基本 URI 解析相对 URI,或在基本 URI 不可用的情况下,将它们解析为相对于当前工作目录的文件路径。使用绝对 URI 保持不变。如果无法定位模块,从而无法获得位置提示,那么处理器会将其忽略,除非无法为名称空间加载任何模块,在这种情况下,处理器会忽略错误消息。
过程
在 XStaticContext 接口上使用 setModuleResolver 方法,以注册模块解析器。
getModule 方法会返回 java.util.List 接口的实例。这是因为针对特定名称空间和位置提示集合,可能有多个模块文档。
示例
以下是使用模块解析器的基本示例。
XFactory factory = XFactory.newInstance();
// Create the static context
XStaticContext staticContext = factory.newStaticContext();
// Create the module resolver and register it with the static context.
staticContext.setModuleResolver(new AModuleResolver(replacementBase));
// Prepare the query.
XQueryExecutable executable = factory.prepareXQuery(new StreamSource(queryFile), staticContext);
// Execute the transformation.
Source source = new StreamSource(inputFile);
Result result = new StreamResult(System.out);
executable.execute(source, result);
以下是模块解析器实现的基本示例。
class AModuleResolver implements XModuleResolver
{
String _replacementBase;
public AModuleResolver(String replacementBase)
{
_replacementBase=replacementBase;
}
// Resolve URI, returning the Source that URI represents.
// Implements the "rebase:" pseudo-scheme.
public List<? extends Source> getModule(String namespace, List<String> locations, String baseURI) {
String rebasePrefix="rebase:";
List<StreamSource> list = new ArrayList<StreamSource>();
for (int i = 0; i < locations.size(); i++) {
String href = locations.get(i);
String base = baseURI;
if(href.startsWith(rebasePrefix)) {
href=href.substring(rebasePrefix.length());
base=_replacementBase;
}
java.net.URI uri;
StreamSource source=null;
try {
// Get base URI object
uri = new java.net.URI(base);
// Resolved relative reference against base URI
URI resolvedURI = uri.resolve(href);
// Try to read...
source = new StreamSource(resolvedURI.toString());
} catch (java.net.URISyntaxException use) {
throw new RuntimeException(use);
}
list.add(source);
}
return list;
}
}