dinesh028
dinesh028

Reputation: 2187

Get position of element

Suppose I have a xml

<Root>
<TB>
..
</TB>
<TB>
..

</TB>
<TB>
..
<DIACT>2</DIACT>
</TB>
<TB>
...
<DIACT>3</DIACT>
</TB>
<TB>
----
<DIACT>4</DIACT>
---
</TB>
</Root>

I want to get the position of first TB node where DIACT is not null or DIACT node exist, using xslt mapping. Like in this case postion should give me output as 3. As 3rd TB node is the first one with DIACT not null.

Upvotes: 0

Views: 155

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243449

Use:

count(/*/TB[DIACT][1]/preceding-sibling::TB) +1

As you need this for futher procesing, set a variable that has the above value:

<xsl:variable name="vPos" 
              select="count(/*/TB[DIACT][1]/preceding-sibling::TB) +1"/>

Alternatively, one can use xsl:number :

  <xsl:variable name="vPos2">
    <xsl:number count="TB"/>
  </xsl:variable>

Here is a simple demo of the two techniques:

 <xsl:template match="/">
    <xsl:variable name="vPos"
        select="count(/*/TB[DIACT][1]/preceding-sibling::TB) +1"/>

    <xsl:value-of select="$vPos"/>
=========== 
    <xsl:for-each select="/*/TB[DIACT][1]">
      <xsl:variable name="vPos2">
        <xsl:number count="TB"/>
      </xsl:variable>
      <xsl:value-of select="$vPos2"/>
    </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<Root>
    <TB> .. </TB>
    <TB> ..  </TB>
    <TB> .. 
        <DIACT>2</DIACT>
    </TB>
    <TB> ... 
        <DIACT>3</DIACT>
    </TB>
    <TB> ---- 
        <DIACT>4</DIACT> --- 
    </TB>
</Root>

two correct results are produced:

3
=========== 
3

Upvotes: 1

Related Questions