个性化阅读
专注于IT技术分析

XQuery If Then Else语句

本文概述

XQuery If Then Else语句用于检查传递的输入值的有效性。

if (condition) then
 ... 
else
 ...

XQuery If Then else示例

让我们以一个示例来演示XQuery中if-then-else语句的用法。取一个名为books.xml的XML文件, 并对其应用XQuery表达式, 该表达式包含if-then-else构造, 以检索价格大于100的那些书的书名。

XML陈述式

books.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
   <book category="JAVA">
      <title lang="en">Learn Java Programming</title>
      <author>Sonoo Jaiswal</author>
      <year>2012</year>
      <price>400.00</price>
   </book>
   
   <book category="DOTNET">
      <title lang="en">DOTNET Fun</title>
      <author>Balaswamy</author>
      <year>2008</year>
      <price>300.50</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XQuery in 1 month</title>
      <author>Ajeet Kumar</author>
      <author>Sam Lee</author>
      <year>2013</year>
      <price>250.00</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XPath in 1 month</title>
      <author>Ajeet Kumar</author>
      <year>2014</year>
      <price>150.50</price>
   </book>
</books>

XQuery表达式

books.xqy:

<result>
{
   if(not(doc("books.xml"))) then (
      <error>
         <message>books.xml does not exist</message>
      </error>
   )
   else ( 
      for $x in doc("books.xml")/books/book	
      where $x/price>30
      return $x/title
   )
}
</result>

Create a Java based XQuery executor program to read the books.xqy, passes it to the XQuery expression processor, and executes the expression. After that the result will be displayed. 
XQueryTester.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;

import com.saxonica.xqj.SaxonXQDataSource;

public class XQueryTester {
   public static void main(String[] args){
      try {
         execute();
      }
      
      catch (FileNotFoundException e) {
         e.printStackTrace();
      }
      
      catch (XQException e) {
         e.printStackTrace();
      }
   }

   private static void execute() throws FileNotFoundException, XQException{
      InputStream inputStream = new FileInputStream(new File("books.xqy"));
      XQDataSource ds = new SaxonXQDataSource();
      XQConnection conn = ds.getConnection();
      XQPreparedExpression exp = conn.prepareExpression(inputStream);
      XQResultSequence result = exp.executeQuery();
       while (result.next()) {
         System.out.println(result.getItemAsString(null));
      }
   }	
}

对XML执行XQuery

将以上三个文件放在同一位置。我们将它们放在桌面上的文件夹名称XQuery9中。使用控制台编译XQueryTester.java。你必须在计算机上安装JDK 1.5或更高版本, 并且已配置类路径。

编译:

javac XQueryTester.java

执行:

Java XQueryTester

输出

XQUERY if-then-else语句1

下载此示例

赞(0)
未经允许不得转载:srcmini » XQuery If Then Else语句

评论 抢沙发

评论前必须登录!