XQuery工作组于1999年9月正式成立,其任务是创建一种灵活的查询语言以便从XML文档中抽取数据。目前W3C所公布的最新XQuery草案是2003年11月12日的版本,它还在不断的修订和完善之中[1]。作为一种新型的查询语言,XQuery汲取了其它多种查询语言的优点,适用于各种类型的XML数据源的查询,不仅查询功能强大,而且简洁灵活且易于实现。而且,XQuery还具有从多种数据库中检索信息的特点,它能对各种数据和文档进行查询。
XQuery构建在XPath规范之上,其核心是能够通过XPath表达式从文档选择特殊的节点序列。XQuery是一种将查询表示成表达式的功能语言。通过它所支持的多种表达式,它的查询可以有各种不同的形式。各种XQuery表达式可以完全嵌套,也支持子查询。目前,数据库业界的三大主流厂商Oracle、IBM、Microsoft都已经在各自的产品中提供了对XQuery规范的支持。
二 、XQEngine概述
XQEngine是一个实现了XQuery的引擎(开发包),他是开放源代码的、基于 Java 的XML查询引擎。XQEngine的官方网站是www.fatdog.com,XQEngine的下载在sourceforge可以找到。我下载了XQEngine0.6.9.
三、实例代码
XQEngine0.6.9的包中包含了一个SampleApp.java的例子。通过它就可以用来执行XQuery.
下面是我的实例代码:
package william;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.fatdog.xmlEngine.ResultList;
import com.fatdog.xmlEngine.XQEngine;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* @author fuwl
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Search {
private static String XMLFile = "william.xml";
public static void main( String[] args ) throws Exception
{
System.out.println("========XML Search 0.9=====");
System.out.println(" Use XQEngine 0.6.9 ");
System.out.println("===========================");
System.out.println("XML File is:"+XMLFile);
//String query = args[0];
//查询语句(查询bib下的第二个book元素的tiltle)
String query = "/bib/book[2]/title";
System.out.println("query is:"+query);
XQEngine m_engine = new XQEngine();
//设置XQEngine 相关属性
m_engine.setMinIndexableWordLength( 0 );
m_engine.setShowFileIndexing( true );
m_engine.setUseLexicalPrefixes( false );
//installSunXMLReader
SAXParserFactory spf = SAXParserFactory.newInstance();
try
{
SAXParser parser = spf.newSAXParser();
XMLReader reader = parser.getXMLReader();
m_engine.setXMLReader( reader );
}
catch( Exception e )
{
throw e;
}
//加载xml文档
m_engine.setDocument(XMLFile);
//执行查询
ResultList results = m_engine.setQuery( query );
results.getAST().dump(" " );
System.out.println( "Result:" );
if ( results.getNumValidItems() == 0 )
{
System.out.println( "No hits!" );
}
else
{
System.out.println( results.emitXml( true ) );
}
}
}
william.xml的内容:
<bib>
<book year="2005">
<title>TCP/IP ttt</title>
<author><last>fuweilin</last><first>W.</first></author>
<publisher>Addison-Wesley</publisher>
<price> 65.95</price></book>
<book year="2004">
<title>11Advanced Programming in the Unix environment</title>
<author><last>Stevens</last><first>W.</first></author>
<publisher>Addison-Wesley</publisher>
<price>65.95</price></book>
</bib>
程序执行的结果:
Result:
<title>11Advanced Programming in the Unix environment</title>