XSLT - 在谓词过滤器中,为什么有时必须使用 XSLT current() 函数而不是 XPath 上下文节点点号运算符?

4
在一个谓词过滤器中,我正在尝试找出何时以及为什么必须使用XSLT的current()函数而不是XPath上下文节点.表达式。 w3schools的XSLT current() Function页面给出的示例只有一点帮助,因为它似乎主要是说明差异而没有真正解释它。Michael Kay在“XSLT 2.0和XPath 2.0,第4版”的第13章中讨论current()函数以及Paul Jungwirth对问题Current node vs. Context node in XSLT/XPath?的回复帮助我个人理解了差异;但每个答案都让我苦苦思索如何向他人解释这种区别,而不仅仅是用图表和代码来说明差异。如果有人能分享他们进一步解释这一点的方法,我将不胜感激。
3个回答

3
在XPath中,位置路径表达式是相对于上下文节点的,例如:
head/title

或者

@class

谓语用于过滤序列(在v1中是节点集)。谓语表达式针对序列中的每个项目(或节点)使用项目作为上下文进行评估。例如:

div[@class] (: @class is relative to div :)
current()函数仅在XSLT中可用,用于引用当前由包含的xsl:templatexsl:for-each指令处理的节点。

更多信息请参考http://www.w3.org/TR/xslt#function-current


非常简洁的解释,谢谢。 - user3469092
如果您认为这是最有帮助的答案,请考虑接受它。 - Mathias Müller
@MathiasMüller 作为新来的这里,我非常感谢您的建议。谢谢。我想我已经做对了(通过点击复选标记)。 - user3469092

0

在路径表达式中,上下文节点会随着任何步骤和谓词的添加而发生改变,而当前节点只会被 XSLT 指令(如 apply-templates 和 for-each)所更改。


0
通过这段代码,我理解了源代码。
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<parent>
    <variable>A</variable>
    <child>
        <variable>B</variable>
    </child>
</parent>

xslt:

   <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />
    <xsl:template match="/parent">

            <xsl:value-of select="string('using current')"/>
            <xsl:choose>
                <xsl:when test="child[current()/variable = 'A']">
                    <xsl:text>&#10;child[current()/variable = 'A']// -> is true</xsl:text> 
                </xsl:when>
                <xsl:otherwise>
                    <xsl:text>&#10;child[current()/variable = 'A']// -> is false</xsl:text> 
                </xsl:otherwise>
            </xsl:choose>

            <xsl:value-of select="string('&#10;&#10;using dot')"/>
            <xsl:choose>
                <xsl:when test="child[./variable = 'A']">
                    <xsl:text>&#10;child[./variable = 'A']// -> is true</xsl:text> 
                </xsl:when>
                <xsl:otherwise>
                    <xsl:text>&#10;child[./variable = 'A']// -> is false</xsl:text> 
                </xsl:otherwise>
            </xsl:choose>

            <xsl:value-of select="string('&#10;&#10;using dot')"/>
            <xsl:choose>
                <xsl:when test="child[./variable = 'B']">
                    <xsl:text>&#10;child[./variable = 'B']// -> is true</xsl:text> 
                </xsl:when>
                <xsl:otherwise>
                    <xsl:text>&#10;child[./variable = 'B']// -> is false</xsl:text> 
                </xsl:otherwise>
            </xsl:choose>


    </xsl:template>
</xsl:stylesheet>

输出:

using current
child[current()/variable = 'A']// -> is true

using dot
child[./variable = 'A']// -> is false

using dot
child[./variable = 'B']// -> is true

所以,你可以通过使用“current”函数来检查当前节点内的内容,而不是在子节点中像点操作一样。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接