【问题标题】:XSLT: Set multiple variables depending on conditionXSLT:根据条件设置多个变量
【发布时间】:2012-09-01 07:57:18
【问题描述】:

我想根据一个条件环境分配多个变量。我只知道如何为一个变量做到这一点:

<xsl:variable name="foo">
    <xsl:choose>
        <xsl:when test="$someCondition">
            <xsl:value-of select="3"/>
        <xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="4711"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>

但是如果我想根据相同的条件 $someCondition 分配两个变量呢?

我不想再次编写相同的 xsl:choose 语句,因为在实际示例中它有点冗长且计算量很大。

有问题的环境是带有 exslt 扩展的 libxslt (xslt 1.0)。

编辑:我想要的是类似于

if (condition) {
    foo = 1;
    bar = "Fred";
}
else if (...)  {
    foo = 12;
    bar = "ASDD";
}
(... more else ifs...)
else {
    foo = ...;
    bar = "...";
}

【问题讨论】:

    标签: xslt xslt-1.0 exslt


    【解决方案1】:

    你可以让你的主变量返回一个元素列表;每个要设置的变量一个

      <xsl:variable name="all">
         <xsl:choose>
            <xsl:when test="a = 1">
               <a>
                  <xsl:value-of select="1"/>
               </a>
               <b>
                  <xsl:value-of select="2"/>
               </b>
            </xsl:when>
            <xsl:otherwise>
               <a>
                  <xsl:value-of select="3"/>
               </a>
               <b>
                  <xsl:value-of select="4"/>
               </b>
            </xsl:otherwise>
         </xsl:choose>
      </xsl:variable>
    

    然后,使用 exslt 函数,您可以将其转换为“节点集”,然后可用于设置您的各个变量

      <xsl:variable name="a" select="exsl:node-set($all)/a"/>
      <xsl:variable name="b" select="exsl:node-set($all)/b"/>
    

    不要忘记,您需要在 XSLT 中为 exslt 函数声明名称空间才能使其工作。

    【讨论】:

      【解决方案2】:

      但是,如果我想根据相同的情况分配两个变量怎么办? 条件 $someCondition?

      我不想再次编写相同的 xsl:choose 语句,因为它 在实际示例中有点冗长且计算量很大。

      假设变量的值不是节点,这段代码不使用任何扩展函数来定义它们:

      <xsl:variable name=vAllVars>   
           <xsl:choose> 
              <xsl:when test="$someCondition"> 
                  <xsl:value-of select="1|Fred"/> 
              <xsl:when> 
              <xsl:when test="$someCondition2"> 
                  <xsl:value-of select="12|ASDD"/> 
              <xsl:when> 
              <xsl:otherwise> 
                  <xsl:value-of select="4711|PQR" />
              </xsl:otherwise> 
          </xsl:choose> 
      </xsl:variable>   
      
      <xsl:variable name="foo" select="substring-before($vAllVars, '|')"/>
      <xsl:variable name="bar" select="substring-after($vAllVars, '|')"/>
      

      【讨论】:

      • 使用这个,foo 和 bar 将始终具有相同的值。这不是我需要的...请参阅我的编辑以进行澄清。
      • @Jost,是的,请参阅我的更新。每当变量的值不是节点时,根本不构建(和转换)结果树会更容易并且可能更有效。
      • 这个解决方案应该可以工作。但是有一个缺点:您需要一个永远不会出现在任何变量值中的分隔符,这可能很难找到。在选择一个之后,当程序的其他部分发生变化时,这将是一个将来可能出现问题的地方......
      • @Jost:使用类似:$#@!321 :)
      • 那么保证有人会使用这个字符。 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 2020-07-08
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多