Answers:
<xsl:if test="xpath-expression">...</xsl:if>
例如
<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>
html/body and not(html/body/node())即,仅测试它是否存在并且不包含任何子节点或文本节点)。
尝试以下表达式: boolean(path-to-node)
Patrick在使用xsl:if和以及检查节点是否存在的语法方面都是正确的。但是,正如Patrick的回答所暗示的,没有xsl等效于if-then-else,因此,如果您正在寻找更类似于if-then-else的东西,通常最好使用xsl:chooseand xsl:otherwise。因此,帕特里克(Patrick)的示例语法将起作用,但这是另一种选择:
<xsl:choose>
<xsl:when test="/html/body">body node exists</xsl:when>
<xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>
if-then-else,那又如何if-else if-else呢?在davenpcj的答案中,我test="somexpath"何时可以放置在第二个位置if-else if-else?
使用选择可能更好,不必多次键入(或可能键入错误)表达式,并允许您遵循其他不同的行为。
我经常使用count(/html/body) = 0,因为特定数量的节点比集合更有趣。例如...当意外地有多个节点与您的表达式匹配时。
<xsl:choose>
<xsl:when test="/html/body">
<!-- Found the node(s) -->
</xsl:when>
<!-- more xsl:when here, if needed -->
<xsl:otherwise>
<!-- No node exists -->
</xsl:otherwise>
</xsl:choose>
count(/html/body) = 0 天才 !:DI使用它/html[count(/body)=0]/someNode来选择someNode何时/body(或什么时候)丢失
/html[count(/body)=0]将永远不会选择任何内容,XML中不能有两个根节点。也许您的意思/html[count(body)=0]是与/html[not(body)]或相同/html[not(exists(body))]。