1

How can I get the position of a node based on a certain attribute value? The following post shows how to do this with elements:

Find position of a node using xpath

So if we change the example xml in the post mentioned above to:

<a>
    <b val="zyx" />
    <b val="wvu" />
    <b val="tsr" />
    <b val="qpo" />
</a>

How would I get the position of a/b[@val = 'tsr']?

Community
  • 1
  • 1
rokeefe1
  • 25
  • 5

1 Answers1

1

Should be almost exactly the same:

count(a/b[@val='tsr']/preceding-sibling::*)+1

Example usage...

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:value-of select="count(a/b[@val='tsr']/preceding-sibling::*)+1"/>
  </xsl:template>

</xsl:stylesheet>

Output:

3
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • Did you test your solution? When I copy your solution verbatim and run it against my test file I get an output of 1. I tried something similar to what you posted before posting this question and I was still getting 1 instead of 3 – rokeefe1 Mar 09 '12 at 17:05
  • @user1252899 - Yes I did. I tested with Xalan, Saxon 6.5.5, Saxon 9.3 (HE, PE, and EE), and AltovaXML and all give me the result of "3". Is your test file exactly the same as the XML posted in the question? What processor are you using? – Daniel Haley Mar 09 '12 at 18:05
  • The problem was in my XML file. Thanks for your help! – rokeefe1 Mar 19 '12 at 14:27