Search code examples
xmlxpathtop-n

How to get the TOP N element corresponding to a condition with XPath


I have an XML like this

<root>
<el id="1" value="3"/>
<el id="2" value="3"/>
<el id="3" value="4"/>
<el id="4" value="4"/>
<el id="5" value="4"/>
<el id="6" value="4"/>
</root>

I'd like with one xpath (I'm in a c# context not an xslt template) get the 2 first element with a value of 4 ie

<el id="3" value="4"/>
<el id="4" value="4"/>

with /root/el[position() <= 2 and @value=4] I'd get 0 element because position() is based on the parent node, not the current subset.

I can do this in c# but it seems useless to load 1200 node when I only need 20.

Thanks


Solution

  • The following works for me in an XSLT script;

      <xsl:template match="/">
        <xsl:apply-templates select="/root/el[@value=4][position()&lt;=2]" />
      </xsl:template>
    

    The result is id's 3 and 4, so the XPATH /root/el[@value=4][position()&lt;=2] should work for you.