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

ran*_*its 9 xml xslt

是否可以使用<xsl:value-of>?设置默认值?我试图使用XSLT样式表生成JSON输出,并且在处理阶段可能无法使用某些字段.这会留下一个空值,这会破坏JSON文档的有效性.理想情况下,如果没有默认值,我可以设置默认值.所以在以下情况下:

    "foo_count": <xsl:value-of select="count(foo)" />
Run Code Online (Sandbox Code Playgroud)

如果<foo>文档中没有,我可以将其设置为0吗?

G. *_*man 15

XSLT/XPath 2

使用序列表达式:

<xsl:value-of select="(foo,0)[1]"/>
Run Code Online (Sandbox Code Playgroud)

说明

构造序列的一种方法是使用逗号运算符,该运算符 计算每个操作数并将结果序列按顺序连接成单个结果序列.

  • 我不是给定的“解释”的作者,这是不正确的。逗号运算符只是计算给定表达式中的一系列项。正如编写该解释的人所说,没有串联。在我的回答中,括号围绕着最多两个值的序列表达式:“foo”的求值和“0”的求值。不存在的值不会出现在序列中,因此如果 &lt;foo&gt; 子项不存在,则序列只有一项,即 0,因此返回。如果 &lt;foo&gt; 孩子确实存在,则返回它。没有串联。 (5认同)

ren*_*ene 13

它要么选择

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

或使用,如果测试

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

或使用命名模板进行呼叫

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


Édo*_*pez 7

XSLT/XPath 2.0

您可以在表达式if…then…else上使用条件表达式()@select:

<xsl:value-of select="if (foo) then foo else 0" />
Run Code Online (Sandbox Code Playgroud)