我正在创建XSLT文件.我有一个从XML文件获取值的变量.但是可能会发生xml中没有值的引用,那时XSL变量将返回False/None(不知道).我想要保持条件,如果变量没有值使用默认值.怎么做 ?
Dir*_*mar 28
通过问题中给出的一些细节,您可以做的最简单的测试是:
<xsl:if test="$var">
...
</xsl:if>
Run Code Online (Sandbox Code Playgroud)
或者,xsl:choose如果要为else-case提供输出,则可以使用:
<xsl:choose>
<xsl:when test="not($var)"> <!-- parameter has not been supplied -->
</xsl:when>
<xsl:otherwise> <!--parameter has been supplied --> </xsl:otherwise>
</xsl:choose>
Run Code Online (Sandbox Code Playgroud)
第二个例子也将正确处理这个案例,即变量或参数没有提供实际值,即它等于空字符串.这有效,因为not('')返回true.
Dim*_*hev 15
你没有用"没有价值"来解释你的意思.这是一个通用的解决方案:
not($v) and not(string($v))
Run Code Online (Sandbox Code Playgroud)
此表达式求值为true()iff $v"没有值".
这两个条件需要满足,因为一个字符串$v定义为'0'具有价值,但not($v)是true().
在XSLT 1.0中,如果"value"是节点集或者值是标量(例如字符串,数字或布尔值),则可以使用不同的方式实现默认值.
如果应该包含节点集的变量为空,则@Alejandro提供了一种获取默认值的方法.
如果变量应该包含标量,则以下表达式返回其值(如果它具有值)或(否则)返回所需的默认值:
concat($v, substring($default, 1 div (not($v) and not(string($v)))))
Run Code Online (Sandbox Code Playgroud)
您可以使用string-length来检查$reference例如调用的变量是否包含任何内容。
<xsl:choose>
<xsl:when test="string-length($reference) > 0">
<xsl:value-of select="$reference" />
</xsl:when>
<xsl:otherwise>
<xsl:text>some default value</xsl:text>
</xsl:otherwise>
</xsl:choose>
Run Code Online (Sandbox Code Playgroud)
如有必要normalize-space,也使用。