(我发布这个自我回答的问题是因为通常为这个问题提供的解决方案是不必要的冗长,我想澄清一下。我找不到现有的 SO 问题,但如果有的话,请将此作为副本关闭。)
我正在寻找一种方法来执行 XPath 选择以仅在当前节点匹配特定条件时才选择它。例如,当我想有条件地将 XSLT 模板应用于当前节点时,这将很有用:
<xsl:template match="Device">
<div>
<h2><xsl:value-of select="Name" /></h2>
<xsl:apply-templates select="???[Featured = 'true']" mode="featured" />
<p><xsl:value-of select="Description" /></p>
</div>
</xsl:template>
<xsl:template match="Book">
<div>
<h2><xsl:value-of select="Title" /></h2>
<xsl:apply-templates select="???[FeaturedBook = 'true']" mode="featured" />
<h3><xsl:value-of select="Author" /></h3>
<p><xsl:value-of select="Summary" /></p>
</div>
</xsl:template>
<xsl:template match="node()" mode="featured">
<p class='featured-notice'>This is a featured item!
<a href="/AddToCart?productId={Id}">Buy now</a> to get a 15% discount.
</p>
</xsl:template>
我试过使用.[Featured = 'true']
,但出现语法错误。我怎样才能做到这一点?
我不打算在这里添加输入和输出,因为它们与问题相切并且会使其非常长,但是如果您想看看我的想法,我将它们放在这里:input,output。