Get current xpath nodes

I need to get the xpath of the current node for which I wrote an xsl function

<func:function name="fn:getXpath">
    <xsl:variable name="xpath">
        <xsl:for-each select="ancestor-or-self::*">
            <xsl:value-of select="concat($xpath, name())" />
            <xsl:if test="not(position()=last())">
                <xsl:value-of select="concat('/', $xpath)" />
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>
    <func:result select="$xpath" />
</func:function>

But when I run this, I get the following error

file:///D:/test.xsl; Line #165; Column #63; Variable accessed before it is bound!
file:///D:/test.xsl; Line #165; Column #63; java.lang.NullPointerException

I am using xalan 2.7.0. Please, help.

+3
source share
2 answers

You use the variable $xpathinside the definition of the variable itself:

<func:function name="fn:getXpath">
    <xsl:variable name="xpath">  
        <xsl:for-each select="ancestor-or-self::*">
            <xsl:value-of select="concat($xpath, name())" />   <-------
            <xsl:if test="not(position()=last())">
                <xsl:value-of select="concat('/', $xpath)" />  <-------
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>
    <func:result select="$xpath" />
</func:function>

The variable is not known at this point.

+2
source

In your example, you are trying to use a variable in the definition itself, which is not valid.

In my opinion, you intend to try to change the value of the existing value. However, XSLT is a functional language, and as a result, variables are immutable. This means that you cannot change the value after the definition.

. ,

<func:function name="fn:getXpath">
   <xsl:variable name="xpath">
      <xsl:for-each select="ancestor-or-self::*">
         <xsl:value-of select="name()"/>
         <xsl:if test="not(position()=last())">
            <xsl:value-of select="'/'"/>
         </xsl:if>
      </xsl:for-each>
   </xsl:variable>
   <func:result select="$xpath" />
</func:function> 
+6

All Articles