如何使用 XSL 检查值是否为空或为空?
例如,如果categoryName
是空的?
这可能是最简单的 XPath 表达式(接受答案中的表达式提供了相反的测试,如果否定,会更长):
not(string(categoryName))
说明:
not()
上述函数的参数false()
恰好是上下文项没有categoryName
子项(“null”),或者(单个这样的)categoryName
子项具有字符串值——空字符串。
我在选择构造时使用。
例如:
<xsl:choose>
<xsl:when test="categoryName !=null">
<xsl:value-of select="categoryName " />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="other" />
</xsl:otherwise>
</xsl:choose>
在 XSLT 2.0 中使用:
<xsl:copy-of select="concat(categoryName, $vOther[not(string(current()/categoryName))])"/>
这是一个完整的例子:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="vOther" select="'Other'"/>
<xsl:template match="/">
<xsl:copy-of select="concat(categoryName,$vOther[not(string(current()/categoryName))])"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于以下 XML 文档时:
<categoryName>X</categoryName>
产生了想要的正确结果:
X
应用于此 XML 文档时:
<categoryName></categoryName>
或对此:
<categoryName/>
或在此
<somethingElse>Y</somethingElse>
产生正确的结果:
Other
同样,使用这个XSLT 1.0转换:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="vOther" select="'Other'"/>
<xsl:template match="/">
<xsl:copy-of select=
"concat(categoryName, substring($vOther, 1 div not(string(categoryName))))"/>
</xsl:template>
</xsl:stylesheet>
请注意:根本没有使用条件。在这个不错的 Pluralsight 课程中了解更多关于避免条件构造的重要性:
“ .NET 中的战术设计模式:控制流”