现在很多开源组织和公司针对XQuery参考规范实现了查询引擎,比较有代表性的是XQEngine、Saxon、Galax等开源XQuery引擎,BEA公司的Aqualogic,DataDirect公司的DataDirect Xquery。
1.安装datadirectxquery.jar,以得到ddxq.jar文件
要想在java中使用Xquery,则需要有XQJ。因此需要下载datadirectxquery.jar,此jar文件在我的个人资源有分享。下载后在cmd中运行
jar xvf datadirectxquery.jar解压,然后双击 XQueryInstaller.jar 文件。如果系统中安装了 Java,将打开 GUI 安装程序。按照默认进行安装。 2.编写java程序,运行在eclipse中新建一个Java Project项目,右击项目点Property,左侧点击Java Build Path,选择Libraries,点Add External Jars,选择你安装xquery里lib文件夹的ddxq.jar,就添加成功了。然后新建XQueryTester.java文件,建立/访问 XQuery 数据源和执行 XQuery。 XQueryTester.java文件的具体内容为
import javax.xml.namespace.QName; import java.util.Properties; import com.ddtek.xquery3.XQConnection; import com.ddtek.xquery3.XQException; import com.ddtek.xquery3.XQExpression; import com.ddtek.xquery3.XQItemType; import com.ddtek.xquery3.XQSequence; import com.ddtek.xquery3.xqj.DDXQDataSource; public class XQueryTester { // Filename for XML document to query private String filename; // Data Source for querying private DDXQDataSource dataSource; // Connection for querying private XQConnection conn; public XQueryTester(String filename) { this.filename = filename; } public void init() throws XQException { dataSource = new DDXQDataSource(); conn = dataSource.getConnection(); } public String query(String queryString) throws XQException { XQExpression expression = conn.createExpression(); expression.bindString(new QName("docName"), filename, conn.createAtomicType(XQItemType.XQBASETYPE_STRING)); XQSequence results = expression.executeQuery(queryString); return results.getSequenceAsString(new Properties()); } public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: java ibm.dw.xqj.XQueryTester [XML filename]"); System.exit(-1); } try { String xmlFilename = args[0]; XQueryTester tester = new XQueryTester(xmlFilename); tester.init(); final String sep = System.getProperty("line.separator"); String queryString = "declare variable $docName as xs:string external;" + sep + " for $cd in doc($docName)/CATALOG/CD " + " where $cd/YEAR > 1980 " + " and $cd/COUNTRY = ‘USA‘ " + " order by $cd/YEAR " + " return " + "<cd><title>{$cd/TITLE/text()}</title>" + " <year>{$cd/YEAR/text()}</year></cd>"; System.out.println(tester.query(queryString)); } catch (Exception e) { e.printStackTrace(System.err); System.err.println(e.getMessage()); } } }