Open In App

XQuery If Then Else

Last Updated : 09 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In XQuery, the ‘if-then-else’ construct is used for conditional processing. It is very useful to check the validity of the input values passed.

Syntax:

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

 

 

Example:

In this example, we use XQuery to process the XML data, evaluate grades using ‘if-then-else’, and generate an output with student names and their respective grades.

XML




<?xml version="1.0" encoding="UTF-8"?>
<students>
  <student>
    <name>Alice</name>
    <grade>85</grade>
  </student>
  <student>
    <name>Bob</name>
    <grade>72</grade>
  </student>
</students>


XML




<!--students.xqy-->
  
let $students :=
 <students>
   <student>
     <name>Alice</name>
     <grade>85</grade>
    </student>
   <student>
     <name>Bob</name>
     <grade>72</grade>
   </student>
 </students>
  
return
 <studentGrades>
  {   
     for $student in $student/student
     return
      <student>
        <name>{data($student/name)}</name>
        <grade>
          {
             let $grade := number($student/grade)
             return 
                if($grade >= 90) then
                  "A"
                else if ($grade >= 80) then
                  "B"
                else
                  "F"
          }
          </grade>
       </student>
   }
</studentGrades>
         


Output:

<studentGrades>
<student>
<name>Alice</name>
<grade>A</grade>
</student>
<student>
<name>Bob</name>
<grade>C</grade>
</student>
</studentGrades>

Example 2:

In this example, we’re processing an XML file representing a fruit basket, extracting the fruits, and generating an output with a structured format called “fruitList” containing the names of the fruits.

XML




<fruitBasket>
  <fruit>Apple</fruit>
  <fruit>Banana</fruit>
  <fruit>Orange</fruit>
</fruitBasket>


XML




let $fruits :=
  <fruitBasket>
    <fruit>Apple</fruit>
    <fruit>Banana</fruit>
    <fruit>Orange</fruit>
  </fruitBasket>
  
return
  <fruitList>
  {
    for $fruit in $fruits/fruit
    return
      <fruit>{data($fruit)}</fruit>
  }
  </fruitList>


Output:

<fruitList>
<fruit>Apple</fruit>
<fruit>Banana</fruit>
<fruit>Orange</fruit>
</fruitList>


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads