What is XQuery Conditional Statement in XML

In this we will discuss about what are conditional statements of XQuery and how we will use it.
  • 2472

Basically, Conditional statements are the selection statement in which we selects a particular statement on the basis of  a particular condition and in XQuery we use "If-then-else" statement for the Conditional Statement and the syntax of using Conditional statement in XQuery is as follows:

if(<expression1>)
then
  <expression2>
else
  <expression3>

Here if the expression1 will be true then expression2 will get executed otherwise expression3 will get executed and one more thing should be noticed here that the test expression must be enclosed within the parenthesis and the else expression is required. Suppose we have the following XML Document.

<?xml version="1.0" encoding="utf-8" ?>

<Inventory>

  <item category="mobile">

    <id>m01</id>

    <price>10000</price>

  </item>

  <item category="Television">

    <id>t01</id>

    <price>50000</price>

  </item>

  <item category="CDPlayer">

    <id>c01</id>

    <price>30000</price>

  </item>

</Inventory>

Now look at the following example.

for $y in doc("Store.xml")/Inventory/item
return if ($y/@category="Television")
then <child>{data($y/id)}</child>
else <adult>{data($y/id)}</adult>

Now in this XQuery if the category of the item will be "Television" then it will return the content of the corresponding id in the form of child node otherwise in the form of adult node.

Output:

<adult>m01</adult>
<child>t01</child>
<adult>c01</adult>

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.