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
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>
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.
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);
//...
}
}
精彩评论