2012-04-17 48 views
13

下面给出的两个代码有什么区别?这两个代码检查在标签中是否存在一个属性:XSLT属性何时与是否有什么区别

<xsl:choose> 
    <xsl:when test="string-length(DBE:Attribute[@name='s0SelectedSite']/node()) &gt; 0"> 
    <table> 
     ... 
    </table> 
    </xsl:when> 
    <xsl:otherwise> 
    <table> 
     ... 
    </table> 
    </xsl:otherwise> 
</xsl:choose> 

<xsl:if test="@Col1-AllocValue"> 
    <xsl:copy-of select="@Col1-AllocValue"/> 
</xsl:if> 

回答

2

choose允许您测试多个条件,只适用于当一个(或默认情况下)相匹配。使用if您也可以测试,但它们会被独立测试,并且每个匹配的案例都会有输出。

中添加更多细节(抱歉不得不赶去)

choose让你测试多个的情况下,只生成的情况下输出的条件匹配的一个,或者产生一些默认的输出。例如:

<xsl:choose> 
    <xsl:when test='@foo=1'><!-- do something when @foo is 1--></xsl:when> 
    <xsl:when test='@foo=2'><!-- do something when @foo is 2--></xsl:when> 
    <xsl:when test='@foo=3'><!-- do something when @foo is 3--></xsl:when> 
    <xsl:otherwise><!-- this is the default case, when @foo is neither 1, 2 or 3--></xsl:otherwise> 
</xsl:choose> 

正如你所看到的“分支”的一个采取取决于@foo值。

随着if,这是一个单一的测试和对测试结果产生输出:

<xsl:if test='@foo=1'><!-- do this if @foo is 1--></xsl:if> 
<xsl:if test='@foo=2'><!-- do this if @foo is 2--></xsl:if> 
<xsl:if test='@foo=3'><!-- do this if @foo is 3--></xsl:if> 

的这里并发症是失败案例 - 当@foo既不是1,2或3,会发生什么?这种遗漏的情况是由choose整齐处理的 - 即具有默认动作的能力。

XSL也缺乏“其他”,你和大多数语言中找到,它允许您提供一个替代的行动应在if测试失败 - 用单个when一个chooseotherwise让你解决这个问题,但在上面我举的例子,这将是可怕的(说明为什么你不这样做..)选择

<xsl:choose> 
    <xsl:when test='@foo=1'><!-- do something when @foo is 1--></xsl:when> 
    <xsl:otherwise> <!-- else --> 
    <xsl:choose> 
     <xsl:when test='@foo=2'><!-- do something when @foo is 2--></xsl:when> 
     <xsl:otherwise> <!-- else --> 
     <xsl:choose> 
      <xsl:when test='@foo=2'><!-- do something when @foo is 2--></xsl:when> 
      <xsl:otherwise><!-- this is the case, when @foo is neither 1, 2 or 3--></xsl:otherwise> 
     </xsl:choose> 
     </xsl:otherwise> 
    </xsl:choose> 
    </xsl:otherwise> 
</xsl:choose> 
+0

需要更多解释。 – 2012-04-17 10:34:35

12

结构

<xsl:choose> 
    <xsl:when test="a">A</xsl:when> 
    <xsl:when test="b">B</xsl:when> 
    <xsl:when test="c">C</xsl:when> 
    <xsl:when test="...">...</xsl:when> 
    <xsl:otherwise>Z</xsl:otherwise> 
</xsl:choose> 

允许含多处e检查和第一次测试的一项操作,评估为truexsl:otherwise用于在没有任何检查评估为true时执行默认操作;特别是这有助于if-then-else的构造(只有一个xsl:when选择加上xsl:otherwise块)。

它总是令我惊讶,xsl:if不允许xsl:else替代,但因为这是在xsl:choose构造中可用,我猜测它被判断不加。也许下一个XSLT版本将包含一个xsl:else

其余的,xsl:whenxsl:if中的测试完全一样:检查条件。

注意的xsl:if结构简单

<xsl:if test="a">A</xsl:if> 

<xsl:when test="a">A</xsl:when> 

将是无效的:xsl:when元素总是xsl:choose一个孩子。而xsl:choose只可能有子女xsl:whenxsl:otherwise

1

下面给出的两个代码有什么区别?这两个代码 检查属性是否存在于标签或不:

这是不正确的

  1. 第一个代码片段表达的如果......那么......否则动作,而第二个片段仅表示如果...动作。

  2. 在提供的两个代码片段中测试的条件 - xsl:when指令和xsl:if指令中的条件是不同的。实际上只有xsl:if(在第二个代码片段中)测试属性的存在。