Search code examples
xmlxpathxpath-1.0

Selecting top N elements


Assuming we have such a structure (the number of b in every a is unknown):

<a>
    <b/>
    <b/>
    <b/>
</a>
<a>
    <b/>
    <b/>
    <b/>
</a>

How would we express the following phrase in xpath: "top 4 b elements nested into a"

The a/b[position() <= 4] for obvious reasons returns all 6 elements.

How would I limit it to 4?

I've found that (a/b)[position() <= 4] should work, but seems it's xpath 2.0. Any ideas for 1.0 version?


Solution

  • Why do you say

    (a/b)[position() <= 4] should work, but seems it's xpath 2.0

    ? That's perfectly legitimate XPath 1.0, and in fact is a common idiom for this purpose. I just tested it to confirm that it's accepted and works correctly.

    It may also be more efficient than using count(preceding::b), depending on the XPath processor.