首页 > 解决方案 > 在 XSLT 1.0 中的 for-each 中的谓词中,current() 引用了什么?

问题描述

我经常看到这样的代码:

<xsl:for-each select="/catalog/cd/artist">
    <xsl:sort select="artist"/>
    ...business logic...
    <xsl:variable name="artistNum" select="artist_number"/>
    <xsl:value-of select="/catalog/cd/song[song_artist_number = $artistNum]/song_title"/>
</xsl:for-each>

该变量artistNum仅使用一次,value-of以确保使用正确的节点。这些数字的作用类似于 SQL 中的外键,但在 XML 中。我在 W3Schools上读到过,current()并且.在一种特定情况下的含义略有不同。所以我想知道以下是否也是正确的,允许artistNum摆脱几乎无用的变量。

<xsl:for-each select="/catalog/cd/artist">
    <xsl:sort select="artist"/>
    ...business logic...
    <xsl:value-of select="/catalog/cd/song[song_artist_number = current()/artist_number]/song_title"/>
</xsl:for-each>

但我不确定current()在这种情况下是否指的是song因为它在谓词中,还是artist来自for-each.

标签: xmlxsltxslt-1.0

解决方案


嗯,current()指的是当前节点。:)

<xsl:for-each select="/catalog/cd/artist">
    <!-- processes `<artist>` elements - current() always refers to that element --->
</xsl:for-each>

current()存在以克服.引用 XPath 谓词正在操作的节点的问题,并且 XPath(从其有限的世界视图中)无法访问 XSLT 的上下文。

这是没有意义的,因为<artist_number>可能不是以下的孩子<song>

<xsl:value-of select="/catalog/cd/song[song_artist_number = ./artist_number]/song_title"/>

这是有道理的,因为<artist_number>可能的孩子<artist>

<xsl:for-each select="/catalog/cd/artist">
  <xsl:value-of select="/catalog/cd/song[song_artist_number = current()/artist_number]/song_title"/>
</xsl:for-each>

XSLT 中的一些东西改变了current()节点——最显着的是<xsl:for-each><xsl:apply-templates>(但不是<xsl:call-template>)。

从根本上说,.是一个 XPath 概念。它指的是 XPath 表达式中不同位置的不同节点。current()是一个 XSLT 概念。它引用单个节点,直到 XSLT 程序的处理上下文发生变化。它在 XSLT 之外也不可用。


推荐阅读