如果值不存在,XSLT默认变量值是什么?

10

我正在尝试声明一个具有默认值的变量,或者如果在重复集中存在值,则使用新的不同值。

到目前为止,这就是我所拥有的。

      <xsl:variable name="lsind">
        <xsl:value-of select="'N'"/>

        <xsl:for-each select='./Plan/InvestmentStrategy/FundSplit'>
          <xsl:choose>
            <xsl:when test="contains(./@FundName, 'Lifestyle')">
              <xsl:value-of select="'Y'"/>
            </xsl:when>
          </xsl:choose>
        </xsl:for-each>
      </xsl:variable>
我想要的是,如果./Plan/InvestmentStrategy/FundSplit/@FundName中的任何一个实例包含LifeStyle,则lsind为'Y',否则它会退回到默认值'N'。 我这样做是因为如果我使用'otherwise',最后一次出现可能会将lsind设置为N? 有什么建议吗?
2个回答

16
<xsl:variable name="lsind">
  <xsl:choose>
    <xsl:when test="Plan/InvestmentStrategy/FundSplit[contains(@FundName, 'Lifestyle')]">
       <xsl:text>Y</xsl:text>
    </xsl:when>
    <xsl:otherwise>
       <xsl:text>N</xsl:text>
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

应该足够


1
你是一个美丽的人。谢谢!我刚开始探索XPath路线,怀疑一定有办法。 - Jon H

6

这可以在一个XPath表达式中指定(即使是在XPath 1.0中):

 <xsl:variable name="vLsind" select=
 "substring('YN',
             2 - boolean(plan/InvestmentStrategy/FundSplit[@FundName='Lifestyle']),
             1)"/>

例子1:

<plan>
 <InvestmentStrategy>
  <FundSplit FundName="Lifestyle"/>
 </InvestmentStrategy>
</plan>

转换:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:variable name="vLsind" select=
 "substring('YN',
             2 - boolean(plan/InvestmentStrategy/FundSplit[@FundName='Lifestyle']),
             1)"/>

 <xsl:template match="/">
   <xsl:value-of select="$vLsind"/>
 </xsl:template>
</xsl:stylesheet>

结果:

Y

示例2:

<plan>
 <InvestmentStrategy>
  <FundSplit FundName="No Lifestyle"/>
 </InvestmentStrategy>
</plan>

结果:

N

解释:

  1. 根据定义,当some-node-set非空时,boolean(some-node-set)true()

  2. 根据定义,number(true())1,而number(false())0

  3. 1和2结合起来得出: 当some-node-set非空时,number(boolean(some-node-set))1,否则为0

其他单表达式解决方案:

XPath 1.0:

translate(number(boolean(YourXPathExpression)), '10', 'YN')

XPath 2.0:

if(YourXPathExpression)
 then 'Y'
 else 'N'

甚至更好:
 ('N', 'Y')[number(boolean(YourXPathExpression)) +1]

4
@Goran:这是警察局说的吗?如果“this”是滥用,那么我会遇到更大的麻烦... :) (说明:“this”前面的上下文信息缺失,因此无法确定具体指什么。) - Dimitre Novatchev
@DimitreNovatchev。这并不是滥用,但它可能非常晦涩,因为它掩盖了表达式中的逻辑结构,这对于长期维护可能不利,因为大多数人或者接替他们的人每次重新访问时都需要努力理解它。 - Patanjali
@Patanjali,唯一保留的命名空间前缀是:"xml"和"xmlns" -- 我认为这样做是为了避免出现太多的"禁用前缀"。XQuery还预定义了XML Schema命名空间的前缀"xs"。至于使用缩写前缀来表示XSLT命名空间,这可能会影响一些硬编码只能理解"xsl:"的XSLT IDEs。 - Dimitre Novatchev
@Patanjali:关于“不幸的是,XSL的设计者让它变得非常啰嗦”的问题——这实际上是一件好事——它使代码更易读且容错率更高,可以将语言的一个有效语法标记转换为另一个有效的语法标记时,更容易发现打字错误。自2000年以来,没有其他人抱怨过XSLT很“啰嗦”——大多数人使用XSLT IDE,具有智能提示和自动完成功能,因此程序员从不编写整个XSLT标记——只需点击几个键即可。 - Dimitre Novatchev
一个比我更好地解释这个问题的人,当然是迈克尔·凯博士(@michael-kay)。 - Dimitre Novatchev
显示剩余11条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接