views:

141

answers:

4

I have a for-each and when there is nothing output by it I would like to display some default text.

If I have...

<xsl:for-each select='xpath'> Some content for each matching element result. </xsl:for-each>

What I would like is:

<xsl:for-each select='xpath'>
   <xsl:output-this-when-there-is-content> Some content for each matching element result. </xsl:output-this-when-there-is-content>
   <xsl:no-results-output> Some content for when the for-each finds no matches. </xsl:no-results-output>
</xsl:for-each>

Can anyone tell me how to do this, please?

Thanks,

Matt

A: 
foreach (var x in variable)
{
    if(!x)
    {
       Console.Writeline("your text");
    }

    //...
}

Is it this, what you wanted??

cordellcp3
In the tags "xpath" was specified, so I think he meant <xsl:for-each> in a xslt file.
Hans Kesting
Tags say XPATH, so one should assume the OP means XSLT-foreach?
Thorsten Dittmar
Yes, it was an XPath query. But it's always nice to get help for the future :)
Matt W
+3  A: 

Assuming you have:

<xsl:for-each select="xpath"> ...

The you can do something like:

<xsl:choose>
    <xsl:when test="xpath">
        <xsl:for-each select="xpath"> ...
    </xsl:when>
    <xsl:otherwise>
        <xsl:text>Some default text</xsl:text>
    </xsl:otherwise>
</xsl:choose>

To avoid the double test of the XPath (and duplication) you could probably use an xsl:variable, something like the following (syntax may be a little wrong, but the rough idea should be right).

<xsl:choose>
    <xsl:variable name="elems" select="xpath"/>
    <xsl:when test="$elems">
        <xsl:for-each select="$elems"> ...
    </xsl:when>
    <xsl:otherwise>
        <xsl:text>Some default text</xsl:text>
    </xsl:otherwise>
</xsl:choose>
Greg Beech
Thank you, this is exactly what I needed. Is there a faster method than testing the xpath query twice?
Matt W
Thank you, I had not considered using the variable to store the result of the test:)
Matt W
A: 

I would think sth like this would be good:

If (x!=null)
{
console.write("Default Text")}
else
{
foreach (var y in x)
{

       Console.Writeline(y);
    //...
}
}
tuanvt
+1  A: 

To avoid the verbosity of the <xsl:choose> solution that Greg Beech proposed, you can do:

<xsl:variable name="elems" select="xpath"/>

<xsl:for-each select="$elems">
  <!-- ... -->
</xsl:for-each>

<xsl:if test="not($elems)">
  <xsl:text>Some default text</xsl:text>
</xsl:if>

The <xsl:variable> is for efficiency, it avoids doing the same query twice.

The <xsl:for-each> only runs if there are any nodes in $elems, the <xsl:if> only runs if there are not.

Tomalak