如何使用XSL检查值是否为null或空?
例如,如果categoryName
为空怎么办?
这可能是最简单的XPath表达式(接受答案中提供了相反的测试,并且如果取反,将更长):
not(string(categoryName))
解释:
上述not()
函数的参数 false()
恰好在以下情况下成立: 上下文项中不存在categoryName
子元素(即“null”),或者(唯一的)categoryName
子元素具有空字符串的字符串值。
I'm using a when choosing construct.
For example:
<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战术设计模式:控制流”。
xsl:when
进行节点测试。考虑使用<xsl:template match="Category[categoryName[not(node())]]">...</xsl:template>
和<xsl:template match="Category">...</xsl:template>
。处理器将为您做出正确的决策,您无需再嵌套编写业务逻辑的xsl:choose
。在许多情况下,使用匹配模板可以使样式表编写更加容易。 - Abel