Skip to main content

XQuery If Then Else Statement

XQuery If Then Else Statement

XQuery provides a very useful if-then-else construct for checking the validity of passed input values.

Syntax

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

Example

Consider the following example that contains information about a bookstore.

books.xml
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tom Nolan</author>
<year>2022</year>
<price>39.99</price>
</book>
<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<year>2022</year>
<price>9.99</price>
</book>
</bookstore>

We want to use the if-then-else statement to retrieve the titles of those books with a price value that is greater than 20.

The following XQuery expression is to be applied on the above XML document.

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")/bookstore/book
where $x/price>20
return $x/title
)
}
</result>

The XQuery expression above will generate the following result:

<result>
<title lang="en">Harry Potter</title>
<title lang="en">Learn XML</title>
</result>