代码改变世界

XML DataBase之Xindice(二)

2011-07-26 18:34  shy.ang  阅读(433)  评论(0编辑  收藏  举报

Xindice编程

Xindice提供了对Java的编程接口:XML:DB API,由XML:DB Initiative开发,类似于关系数据库的JDBC。其他语言也可以使用XML-RPC API

所有的xindice实例都有一个唯一的根collection名字,一般默认为db,但如果有两个xindice实例,那就需要改变其中一个名字(根据system.xml中的提示,去掉注释)。

上一段简单代码吧:

 

/**
* 在Xindice相关jar文件被装载的时候,会出现XMLDBException,errcode为400,no such database。
* 这可能是因为jar文件的位置问题,当从Xindice安装目录中提取jar文件时,正常运行;
* 而当提取其他位置的Xindice的jar文件时,就会出现上述问题。
*/

package org.apache.xindice.shy.test;

import org.xmldb.api.*;
import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;

publicclass Test_addressbook {
publicstaticvoid main(String[] args)throws Exception{
Collection col
=null;
try {
String driver
="org.apache.xindice.client.xmldb.DatabaseImpl";
Class
<?> c = Class.forName(driver);

Database database
= (Database)c.newInstance();
DatabaseManager.registerDatabase(database);

String uri
="xmldb:xindice://localhost:8080/db/addressbook";
col
= DatabaseManager.getCollection(uri);

if(col!=null){

String xpath
="//person[fname='John']";
XPathQueryService service
=
(XPathQueryService) col.getService(
"XPathQueryService", "1.0");
ResourceSet resultSet
= service.query(xpath);
ResourceIterator results
= resultSet.getIterator();

while(results.hasMoreResources()){
Resource res
= results.nextResource();
System.out.println((String)res.getContent());
}
}
else{
System.out.println(
"The collection doesn't exist.");
}
}
catch(XMLDBException e){
System.err.println(
"XML:DB Exception 发生了"+e.errorCode);
}
finally{
if(col!=null){
col.close();
}
}
}
}

Services提供了XML:DB API的扩展,要获得一个服务,需要知道服务的名字和版本,通过collectiongetService(name,version)方法获得。

Resources提供了访问潜在的XML数据比如文本、DOM节点的抽象方法。Xindice只支持XMLResource。在例子中接触了文本内容,但也可以调用getContentAsDom()方法访问DOM节点内容。文本内容比较容易处理的。比如

  XPathQueryService

       XUpdateQueryService

CollectionManagementService

       还有不属于XMLDB但被Xindice支持的有:

       DatabaseInstanceManager

       CollectionManager

最后的col.close()千万不能忘记,否则会造成资源泄露。