Question

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

Was it helpful?

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.

OTHER TIPS

The answer by @rsp is correct, but I'd like to add an explanation. It's not always true that [cond1 and cond2] is equivalent to [cond1][cond2]. You need the second form.

Your expression:

/root/el[position() <= 2 and @value=4]

...selects all el elements that have a value attribute equal to 4 and whose position is less than or equal to 2. There are no such elements in your document.

You want:

/root/el[@value=4][position() <= 2]

...which first selects all el elements that have a value attribute equal to 4 and then filters that list by position, as desired.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top