xslt – 获取当前节点xpath

我需要获取当前节点的xpath,我已经编写了一个xsl函数

<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>

但是当我运行它时,我收到以下错误

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

我正在使用xalan 2.7.0.请帮忙.

最佳答案
您在变量本身的定义中使用变量$xpath:

<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>

此时变量尚不清楚.

转载注明原文:xslt – 获取当前节点xpath - 代码日志