Gandalf
Gandalf

Reputation: 166

Getting childnodes starting with a lesser value with XQuery

I would like to write an XQuery expression to get all childnodes starting with a childnode with a value which is lesser than the value of the previous childnode and ending with the very last childnode. So for the example below I would like to obtain childnodes with value 1 and 2:

<node>
  <childnode>
    <value>4</value>
  </childnode>
  <childnode>
    <value>8</value>
  </childnode>
  <childnode>
    <value>1</value>
  </childnode>
  <childnode>
    <value>2</value>
  </childnode>
</node>

What is the most elegant solution in XQuery 3.1 for doing that?

Best regards

Upvotes: 1

Views: 47

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167436

The tumbling window clause allows expressing that.

XQuery in BaseX

xquery version "3.1";

declare context item := document {
<node>
  <childnode>
    <value>4</value>
  </childnode>
  <childnode>
    <value>8</value>
  </childnode>
  <childnode>
    <value>1</value>
  </childnode>
  <childnode>
    <value>2</value>
  </childnode>
</node>
};

<root>
{
  for tumbling window $w in /node/childnode
  start $s previous $p when xs:decimal($s/value) lt xs:decimal($p/value)
  return $w
}
</root>

Output

<root>
  <childnode>
    <value>1</value>
  </childnode>
  <childnode>
    <value>2</value>
  </childnode>
</root>

Upvotes: 3

Mads Hansen
Mads Hansen

Reputation: 66714

<node>
  <childnode>
    <value>4</value>
  </childnode>
  <childnode>
    <value>8</value>
  </childnode>
  <childnode>
    <value>1</value>
  </childnode>
  <childnode>
    <value>2</value>
  </childnode>
</node>
 /childnode[value lt preceding-sibling::childnode[1]/value][1]
   /(self::childnode|following-sibling::childnode)

Upvotes: 1

Related Questions