注册集合解析器
您可以向 XDynamicContext 注册 XCollectionResolver 接口的实现。
过程
向动态上下文注册集合解析器。
在执行时使用向 XDynamicContext 注册的 XCollectionResolver 实现,以检索与 n:collection 方法的调用中提供的 URI 关联的节点集合。如果未向 XDynamicContext 注册集合解析器,那么 n:collection 的调用将导致可恢复错误,且会为此集合使用空序列。
请注意,集合解析器和 fn:collection 函数不会解析文档 URI。应将源解析器和 fn:doc 函数用于此目的。
示例
以下是使用集合解析器的基本示例。
XFactory factory = XFactory.newInstance();
// Prepare the XPath expression
XPathExecutable executable = factory.prepareXPath("count(collection('typeA-typeB'))"
// Register the collection resolver with the dynamic context
XCollectionResolver collectionResolver = new ACollectionResolver(factory);
XDynamicContext dynamicContext = factory.newDynamicContext();
dynamicContext.setCollectionResolver(collectionResolver);
// Execute the XPath expression
XSequenceCursor cursor = executable.execute(dynamicContext);
以下是 XCollectionResolver 实现的基本示例。
public class ACollectionResolver implements XCollectionResolver {
private XFactory m_factory;
public ACollectionResolver(XFactory factory) {
m_factory = factory;
}
public XSequenceCursor getCollection(String uri, String base) {
// Get the default collection
if (uri.equals("")) {
return getCollection("default", base);
}
// Get the requested collection
ArrayList<XItemView> list = new ArrayList<XItemView>();
StringTokenizer tokenizer = new StringTokenizer(uri, "-");
XSequenceCursor cursor = null;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
XSequenceCursor temp = getNodes(new StreamSource("collections.xml"), "/doc/" + token);
if (cursor == null) {
cursor = temp;
} else {
cursor = cursor.append(temp);
}
}
return cursor;
}
private XSequenceCursor getNodes(Source source, String expression) {
XPathExecutable executable = m_factory.prepareXPath(expression);
XSequenceCursor cursor = executable.execute(source);
return cursor;
}
}