什么时候和XSLT属性有什么区别

Hem*_*mar 15 xml 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>
Run Code Online (Sandbox Code Playgroud)

<xsl:if test="@Col1-AllocValue"> 
    <xsl:copy-of select="@Col1-AllocValue"/>
</xsl:if>
Run Code Online (Sandbox Code Playgroud)

Mae*_*o13 15

选择的结构是

<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>
Run Code Online (Sandbox Code Playgroud)

允许进行多次检查,并对第一次评估的测试执行一次操作true.xsl:otherwise用于在没有任何检查评估时执行默认操作true; 特别是这有利于if-then-else结构(只有一个xsl:when替代加一个xsl:otherwise块).

总是xsl:if让我感到惊讶的是,不允许xsl:else替代,但由于这在xsl:choose构造中是可用的,我想它被判断为不添加它.也许下一个XSLT版本会包含一个xsl:else

对于其余的,测试中xsl:when和测试xsl:if完全相同:检查条件.

注意结构xsl:if很简单

<xsl:if test="a">A</xsl:if>
Run Code Online (Sandbox Code Playgroud)

单身

<xsl:when test="a">A</xsl:when>
Run Code Online (Sandbox Code Playgroud)

将是无效的:xsl:when元素总是一个孩子xsl:choose.并且xsl:choose可以有孩子xsl:whenxsl:otherwise唯一的.


Nim*_*Nim 5

允许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>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,根据 的值选取“分支”之一@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>
Run Code Online (Sandbox Code Playgroud)

这里的复杂之处在于失败情况@foo——当1,2 或 3 都不是时会发生什么?这种缺失的情况是通过- 即具有默认choose操作的能力来巧妙处理的。

XSL 还缺少您在大多数其他语言中找到的“else”,它允许您在测试失败时提供替代操作if- 并且choose带有单个whenotherwise允许您解决此问题,但在上面的示例中,这将是太可怕了(为了证明你为什么不这样做..)

<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>
Run Code Online (Sandbox Code Playgroud)