如何在XSLT中实现if-else语句?
我想在XSLT中实现一个if-else语句,但我的代码只是不parsing。 有没有人有任何想法?
<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>  你必须用<xsl:choose>标签重新实现它: 
  <xsl:choose> <xsl:when test="$CreatedDate > $IDAppendedDate"> <h2> mooooooooooooo </h2> </xsl:when> <xsl:otherwise> <h2> dooooooooooooo </h2> </xsl:otherwise> </xsl:choose> 
 如果语句用于快速检查一个条件。 如果您有多个选项,请使用<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> } 
如果我可以提出一些build议(两年后,但希望对未来的读者有所帮助) :
-  分解常见的h2元素。
-   ooooooooooooo常见的ooooooooooooo文本。
-  如果使用XSLT 2.0, if/then/else了解新的XPath 2.0if/then/else构造。
XSLT 1.0解决scheme(也适用于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解决scheme
 <h2> <xsl:value-of select="if ($CreatedDate > $IDAppendedDate) then 'm' else 'd'"/> ooooooooooooo </h2> 
最直接的做法是做第二个if-test,但条件反转。 这种技术更短,更容易在眼睛上,而且比select时嵌套块更容易获得。
 <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:if test="$CreatedDate <= $IDAppendedDate"> <h2> dooooooooooooo </h2> </xsl:if> 
以下是政府网站样式表中使用技术的真实示例: http : //w1.weather.gov/xml/current_obs/latest_ob.xsl