我试图在XSLT中实现一个if -else语句,但我的代码无法解析。有人有什么想法吗?
<xsl:variable name="CreatedDate" select="@createDate"/>
<xsl:variable name="IDAppendedDate" select="2012-01-01" />
<b>date: <xsl:value-of select="$CreatedDate"/></b>
<xsl:if test="$CreatedDate > $IDAppendedDate">
<h2> mooooooooooooo </h2>
</xsl:if>
<xsl:else>
<h2> dooooooooooooo </h2>
</xsl:else>
如果我可以提供一些建议(两年后,但希望对未来的读者有帮助):
提出公共的h2元素。
把普通的文字剔除。
如果使用XSLT 2.0,请注意新的XPath 2.0 if/then/else结构。
XSLT 1.0解决方案(也适用于XSLT 2.0)
<h2>
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">m</xsl:when>
<xsl:otherwise>d</xsl:otherwise>
</xsl:choose>
ooooooooooooo
</h2>
XSLT 2.0解决方案
<h2>
<xsl:value-of select="if ($CreatedDate > $IDAppendedDate) then 'm' else 'd'"/>
ooooooooooooo
</h2>
If语句仅用于快速检查一个条件。
当你有多个选项时,使用<xsl:choose>,如下所示:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
此外,您可以使用多个<xsl:when>标记来表示If ..Else If或Switch模式,如下图所示:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:when test="$CreatedDate = $IDAppendedDate">
<h2>booooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
前面的例子相当于下面的伪代码:
if ($CreatedDate > $IDAppendedDate)
{
output: <h2>mooooooooooooo</h2>
}
else if ($CreatedDate = $IDAppendedDate)
{
output: <h2>booooooooooooo</h2>
}
else
{
output: <h2>dooooooooooooo</h2>
}