views:

159

answers:

3

Newbie question on xslt. I've multiple xsl:if checks like

<xsl:if test="node/node1"> ...</xsl:if>
...
<xsl:if test="node/node1"> ...</xsl:if>
...
<xsl:if test="node/node1"> ... </xsl:if>

Is there a way to parameterize the test condition to make the code more readable and easy to maintain? Maybe with a variable or something like

<xsl:variable name="node1Present" select="true()"/>
<xsl:if test="$node1Present"> ... </xsl:if>

I don't understand how to construct the variable to reflect the 'test a node exist' (test="node/node1")

+2  A: 
<xsl:variable name="node1Present" select="boolean(node/node1)"/>

For node-sets, boolean() converts to true, if and only if the node-set is not empty.

Chris Lercher
Thanks Chris..!
mickthompson
A: 

In XPath, any expression that does return a truthy (i.e. non-empty) value is considered as true in boolean context.

<xsl:variable name="node1Present" select="node/node1"/>
<xsl:if test="$node1Present"> ... </xsl:if>

It's not that trying it would have made the world explode. ;-)

Tomalak
A: 

Besides the correct answers so far, I would recommend the following refactoring:

Replace:

<xsl:if test="node/node1"> ...</xsl:if> 
... 
<xsl:if test="node/node1"> ...</xsl:if> 
... 
<xsl:if test="node/node1"> ... </xsl:if>

with:

<xsl:if test="node/node1"> ...</xsl:if> 
... 

or with:

... 
<xsl:if test="node/node1"> ... </xsl:if>

That is, put all code that depends on the condition in a single <xsl:if>.

It would be very interesting if you could present code that cannot be refactored in this way. :)

Dimitre Novatchev
well '...' means that between every xsl:if there's other code ... !
mickthompson
@mickthomposn: I know that. What I am saying that this code need not be dispersed at all! You *can* group all dependent code under a single `<xsl:if>`. If you show your code, many people will be able to help you with this, *better*, refactoring.
Dimitre Novatchev