logo图片
XML教程
XQuery教程
XSLT教程
XPath教程

XQuery IF-ELSE

XQuery If Then Else语句

XQuery If Then Else语句用于检查传递的输入值的有效性。
if (condition) then
 ... 
else
 ...

XQuery If Then else示例

让我们以一个示例来演示XQuery中if-then-else语句的用法。取一个名为books.xml的XML文件,并将其应用到包含if-then-else构造的XQuery表达式中,以检索价格大于100的那些书的书名。
XML语句M
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
昵称: 邮箱:
Copyright © 2020 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4