Max
Max

Reputation: 20014

Constructing a sequence of nodes

Is there an easier way to do this

<Elements>
{
    for $i in ("a", "b", "c")
    return <Element name="{$i}"/>
}
</Elements>

in xquery?

Upvotes: 1

Views: 110

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

I also wonder what do you mean by "easier".

Have all items in a variable $seq and use:

for $i in 1 to count($seq)
 return <Element name="{$seq[$i]}"/>

Here is a whole XQuery program:

   let $seq := 1 to 15
    return
        for $i in 1 to count($seq)
          return <Element name="a{$seq[$i]}"/>

and it produces the correct, wanted result:

<Element name="a1"/>
<Element name="a2"/>
<Element name="a3"/>
<Element name="a4"/>
<Element name="a5"/>
<Element name="a6"/>
<Element name="a7"/>
<Element name="a8"/>
<Element name="a9"/>
<Element name="a10"/>
<Element name="a11"/>
<Element name="a12"/>
<Element name="a13"/>
<Element name="a14"/>
<Element name="a15"/>

Upvotes: 0

wcandillon
wcandillon

Reputation: 2176

You can use fn:map() is your XQuery processor has XQuery 3.0 support:

fn:map(function($e){ <Element name="{$e}" /> }, $sequence)

Upvotes: 2

Oliver Hallam
Oliver Hallam

Reputation: 4262

I don't really understand your question. What do you mean by easier?

How about:

<Elements>
  <Element name="a" />
  <Element name="b" />
  <Element name="c" />
</Elements>

Upvotes: 2

Related Questions