由于您$currentID
从上下文节点中选择:
<xsl:variable name="currentID" select="@id" />
您可以使用该current()
函数,该函数始终引用 XSLT 上下文节点:
<xsl:attribute name="class">
<xsl:if test="count($currentPage/ancestor::node[@id = current()/@id]) > 0]">
<xsl:text>descendant-selected </xsl:text>
</xsl:if>
</xsl:attribute>
这样你就不需要变量了。
其他一些注意事项:
- 我建议使用
<xsl:text>
如上所示。这使您可以更自由地格式化代码并避免过长的行。
- 您不需要做 a
count() > 0
,只需选择节点就足够了。如果不存在,则返回空节点集。它总是计算为假,而非空节点集总是计算为真。
@id
如果您在 XSL 样式表中定期引用节点,<xsl:key>
则将变得有益:
<xsl:key name="kNodeById" match="node" use="@id" />
<!-- ... -->
<xsl:attribute name="class">
<xsl:if test="key('kNodeById', @id)">
<xsl:text>descendant-selected </xsl:text>
</xsl:if>
</xsl:attribute>
上面不需要,current()
因为在 XPath 谓词之外,上下文是不变的。另外,我没有count()
节点,因为这是多余的(如解释的那样)。