xquery- how to assign a number(in sequence) when obtaining a number of records via single query using FLWOR expression
Domanda
While trying to process and obtain data from an XML document, I want to obtain a number of records using a single FLWOR expression-- I am doing this by using the 'let' clause to obtain the data-- so I have a number of rows of data.
Eg.
<div id="main">
<p> Text #1</p>
<p> Text #2</p>
<p> Text #3</p>
<p> Text #4</p>
</div>
Now, I understand how to get the 4 'p' elements -- however I would like to also assign a sequence number to each line -- viz. I want to obtain the text this way--
<data>Text #1</data><sequence> Sequence #1</sequence>
<data>Text #2</data><sequence> Sequence #2</sequence>
<data>Text #3</data><sequence> Sequence #3</sequence>
<data>Text #4</data><sequence> Sequence #4</sequence>
Soluzione
There sure is a more elegant way than doing it like this.... but it works:
let $t := <div id="main">
<p>Text A</p>
<p>Text B</p>
<p>Text C</p>
<p>Text D</p>
</div>
for $pos in $t/p/position()
let $p := $t/p[$pos]
return (
<data>{ $p/text() }</data>,
<sequence>Sequence { $pos }</sequence>
)
Altri suggerimenti
While I'm not completely sure what string value you would to have for the <sequence/>
element, one solution could look as follows:
for $p in <div id="main">
<p>Text #1</p>
<p>Text #2</p>
<p>Text #3</p>
<p>Text #4</p>
</div>/p
return (
<data>{ $p/text() }</data>,
<sequence>Sequence { replace($p, 'Text ', '') }</sequence>
)
You can use the at
keyword in the FLWOR expression's for
clause:
declare variable $div :=
<div id="main">
<p> Text #1</p>
<p> Text #2</p>
<p> Text #3</p>
<p> Text #4</p>
</div>;
for $p at $pos in $div/p
return (
<data>{$p/text()}</data>,
<sequence>Sequence #{$pos}</sequence>
)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow