Haradzieniec
Haradzieniec

Reputation: 9340

xslt: the shortest way to write if-statement that is always false

<xsl:if test="(1 &gt; 2)">
</xsl:if>

Is there anything shorter? Tried (false) and ('false') but with no luck.

Upvotes: 0

Views: 1135

Answers (3)

michael.hor257k
michael.hor257k

Reputation: 116993

Shortest in what terms? The string-length of the expression? Try:

<xsl:if test="''">

Or the number of characters you must type? Try:

<xsl:if test="0"> 

Or did you mean the number of evaluations required - which IMHO is the only legitimate question to ask here. If that is the case, then the answer given by Mathias Müller is the one and only correct answer, because the expression used is already a Boolean. Otherwise this would be a question that should appear in a trivia contest, not here.

Upvotes: 3

Matt Hogan-Jones
Matt Hogan-Jones

Reputation: 3113

Mathias Müller's answer is correct and informative, but from a purely pedantic point of view (and you did ask for the shortest false evaluating xsl:if statement!) you can do this:

<xsl:if test="1=0">

It will always evaluate to false, although I'm not really sure what the point of this would be...

Upvotes: 4

Mathias M&#252;ller
Mathias M&#252;ller

Reputation: 22617

You were almost there. This is the correct way to use a boolean:

<xsl:when test="false()">

It is slightly shorter than your solution, but I would not say that brevity matters here. Rather, using booleans for truth tests is a cleaner solution than taking advantage of the "side effects" of number comparisons.

See this answer for more info on how to create booleans in XSLT.

To illustrate this, assume the following

XML input

<?xml version="1.0" encoding="utf-8"?>
<root/>

Stylesheet

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="/root">
      <xsl:choose>
         <xsl:when test="false()">
            <xsl:copy/>
         </xsl:when>
         <xsl:otherwise/>
      </xsl:choose>
   </xsl:template>

</xsl:stylesheet>

If you change false() to true(), the root element is output.

Upvotes: 5

Related Questions