How to use For Clause with XQuery in XML

In this article we will discuss about how to use the For Clause in XQuery against XML.
  • 1857

The For Clause is used in FLWOR expressions of XQuery. The For Clause is like the iteration statement and it is used to bind the variable with all the element of the XML Document which we want. In XQuery we can use the For Clause in many ways and also we can use more than one For Clause in the FLWOR Expressions in XQuery.

If we want to loop a particular number then we need to use to keyword in For Clause like this.

for $y in (1 to 10)
return <result>{$y}</result>

The output will be like this.

<result>1</result>
<result>2</result>
<result>3</result>
<result>4</result>
<result>5</result>
<result>6</result>
<result>7</result>
<result>8</result>
<result>9</result>
<result>10</result>
 

Now, If we have the following XML Document

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

<Customer>

  <product>

    <id>P01</id>

    <name>Car</name>

  </product>

  <product>

    <id>P02</id>

    <name>Bike</name>

  </product>

  <product>

    <id>P03</id>

    <name>Scooter</name>

  </product>

  <product>

    <id>P04</id>

    <name>Television</name>

  </product>

</Customer>
 

If we want we can count the iteration of the loop by using at keyword in For Clause.

for $y at $i in doc("Customers.xml")/Customer/product/name
return <product>{$i}. {data($y)}</product>

The Output will be as follows.

<product>1.Car</product>
<product>2.Bike</product>
<product>3.Scooter</product>
<product>4.Television</product>
 

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.