xsl-list
[Top] [All Lists]

Re: Do something if no items in for-each meet criteria

2003-09-11 21:58:21

"Peter Hollingsworth" <peter(_at_)hollingsworth(_dot_)net> wrote in message
news:5(_dot_)2(_dot_)1(_dot_)1(_dot_)0(_dot_)20030911155720(_dot_)027fe380(_at_)getmail(_dot_)hollingsworth(_dot_)net(_dot_)(_dot_)(_dot_)
I'm trying to
   1) go through a set of nodes
   2) if any matches my criteria, display it
   3) if NONE matches my criteria, display a message like "None"

For example, imagine this xml listing some animals:
<animal>
   <type>snake</type>
   <furry>false</furry>
</animal>
<animal>
   <type>fish</type>
   <furry>false</furry>
</animal>

and this XSL that lists all the ones with fur:
The following animals are furry:<br/>
<xsl:for-each select="animal">
   <xsl:if test="furry = 'true'">
     <xsl:value-of select="type"/><br/>
   </xsl:if>
</xsl:for-each>
[if no animals were furry, print "None are furry"]  <---how can I do this?

Any way I can accomplish what I'm trying to do on the last line above?

Yes.

When the test is so simple (as in your case), one can simply have:

  <xsl:variable name="vFurry" select="animal[fury = 'true']"/>

  <xsl:for-each select="$vFurry">
       <xsl:value-of select="type"/><br/>
  </xsl:for-each>

 <xsl:if test="not($vFurry)">None are furry </xsl:if>


In case the selection criteria is more complex and cannot be specified in a
single XPath expression (try to find such case with XPath2 and XSLT2) then
you have to create an RTF with the results and test its contents.

I would recommend using the "some-true" template of FXSL, which does this
for you conveniently.



=====
Cheers,

Dimitre Novatchev.
http://fxsl.sourceforge.net/ -- the home of FXSL





 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list