📅  最后修改于: 2020-12-26 06:37:56             🧑  作者: Mango
XQuery If Then Else语句用于检查传递的输入值的有效性。
if (condition) then
...
else
...
让我们以一个示例来演示XQuery中if-then-else语句的用法。取一个名为books.xml的XML文件,并对其应用XQuery表达式,该表达式包含if-then-else构造,以检索价格大于100的那些书的书名。
XML陈述式
books.xml
Learn Java Programming
Sonoo Jaiswal
2012
400.00
DOTNET Fun
Balaswamy
2008
300.50
Learn XQuery in 1 month
Ajeet Kumar
Sam Lee
2013
250.00
Learn XPath in 1 month
Ajeet Kumar
2014
150.50
Xquery表达式
books.xqy:
{
if(not(doc("books.xml"))) then (
books.xml does not exist
)
else (
for $x in doc("books.xml")/books/book
where $x/price>30
return $x/title
)
}
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));
}
}
}
将以上三个文件放在同一位置。我们将它们放在桌面上的文件夹名称XQuery9中。使用控制台编译XQueryTester.java。您必须在计算机上安装JDK 1.5或更高版本,并且已配置类路径。
编译:
javac XQueryTester.java
执行:
Java XQueryTester
输出: