The for clause iteratively associates a variable to the values of an expression. Here is an example:
for $i in (1,2,3) return <tuple>{$i}</tuple>
In XQuery, variables are prefixed by the $ sign. The for clause associates the variable i to the items of the sequence (1,2,3). For each variable assignment, the return clause outputs the value contained in the variable i enclosed into a tuple element. Notice that the variable i is enclosed in curly brackets when used in the tuple element constructor of the return clause. This means that the value of the expression, and not the expression itself, must be printed. The query result is as follows:
<tuple>1</tuple> <tuple>2</tuple> <tuple>3</tuple>
More than one variable can be assigned in a for clause, as in the following example:
for $i in (1,2), $j in (1,2) return <tuple> <i>{$i}</i> <j>{$j}</j> </tuple>
which produces the following output:
<tuple> <i>1</i> <j>1</j> </tuple> <tuple> <i>1</i> <j>2</j> </tuple> <tuple> <i>2</i> <j>1</j> </tuple> <tuple> <i>2</i> <j>2</j> </tuple>
Finally, here is an example on XMark documents. The query returns the name and email address of all persons in the document auction.xml. Notice that comments must be introduced between (: and :) signs:
(: The name and email address of all persons :) for $p in doc("auction.xml")/site/people/person return <person> {$p/name} {$p/emailaddress} </person>