Search code examples
xmlxpathxquery

Xquery to find the next to last item


with xml something like:

<item > 
   <datapoint>5</datapoint>
</item>
<item > 
   <datapoint>4</datapoint>
</item>
<item > 
   <datapoint>6</datapoint>
</item>
<item > 
   <datapoint>8</datapoint>
</item>
<item > 
   <datapoint>9</datapoint>
</item>

And the number of items is not a fixed number. I am already retrieving the last() data point, however I now also need to grab the next to last data point. So in this example I need to separately return both the 8 and the 9.


Solution

  • This XQuery should work:

    for $it in $file/item[position()=last() or position()=last()-1]
    return $it/datapoint
    

    Or, you could also use a shorter version:

    for $it in $file/item[position()>=last()-1]
    return $it/datapoint
    

    Output is:

    <datapoint>8</datapoint>
    <datapoint>9</datapoint>