roh*_*hit 3 reflection xslt xpath xalan xslt-1.0
我需要获取当前节点的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>
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,我收到以下错误
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
Run Code Online (Sandbox Code Playgroud)
我正在使用xalan 2.7.0.请帮忙.
在您的示例中,您尝试在定义本身中使用该变量,该变量无效.
看起来您的目的是尝试修改现有值的值.但是,XSLT是一种函数式语言,因此变量是不可变的.这意味着您无法在定义后更改值.
在这种情况下,您不需要这么复杂.您可以删除对变量本身的引用,然后您将获得所需的结果
<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>
Run Code Online (Sandbox Code Playgroud)