选择一个XSLT时设置的默认值不可用

问题描述 投票:8回答:3

是否有可能使用<xsl:value-of>设置默认值?我试图生产使用XSLT样式表JSON输出和处理阶段某些字段可能无法使用。这使得它打破了JSON文件的有效性的空值。理想情况下我可以设置默认值,如果一个不可用。所以在的情况下:

    "foo_count": <xsl:value-of select="count(foo)" />

如果<foo>不可用的文档中,我能不能将其设置为0不知何故?

xml xslt
3个回答
13
投票

它要么choose

<xsl:choose>
   <xsl:when test="foo">
     <xsl:value-of select="count(foo)" />
   </xsl:when>
   <xsl:otherwise>
     <xsl:text>0</xsl:text>
   </xsl:otherwise>
 </xsl:choose> 

或使用if test

<xsl:if test="foo">
  <xsl:value-of select="count(foo)" />
</xsl:if>
<xsl:if test="not(foo)">
  <xsl:text>0</xsl:text>
</xsl:if>

或使用named template for calling

<xsl:template name="default">
  <xsl:param name="node"/>
  <xsl:if test="$node">
      <xsl:value-of select="count($node)" />
    </xsl:if>
    <xsl:if test="not($node)">
      <xsl:text>0</xsl:text>
  </xsl:if>
</xsl:template>

 <!-- use this in your actual translate -->
 <xsl:call-template name="default">
         <xsl:with-param name="node" select="."/>
 </xsl:call-template>

15
投票

XSLT / XPath的2

使用Sequence Expressions

<xsl:value-of select="(foo,0)[1]"/>

说明

构建序列的一种方法是通过使用逗号运算符,其评估每个操作数的并连接所得到的序列,为了成单个结果序列。


7
投票

XSLT / XPath 2.0中

您可以在Conditional Expressions (if…then…else)表达式中使用@select

<xsl:value-of select="if (foo) then foo else 0" />
© www.soinside.com 2019 - 2024. All rights reserved.