Nic Miloslav     Example 25    KEYWORDS      EXAMPLES      AUTHORS     

Sometimes you want to output an element only if it has a value. Stylesheet 1 shows a way how to do it. Function normalize-space removes unsignificant spaces. Stylesheet 2 shows the output without empty elements removal.


     XML     HOME     XSL 1     XSL 2      
<xslTutorial >
<table>
<item> item 1 </item>
<item> item 2 </item>
<item></item>
<item>     </item>
<item> item           3</item>
</table>
</xslTutorial>

     XSL 1     HOME     XML     HTML 1     OUTPUT 1     
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' >
<xsl:template match="table">
<TABLE BORDER='1'>
<xsl:for-each select="item">
<xsl:apply-templates select="."/>
</xsl:for-each>
</TABLE>
</xsl:template>
<xsl:template match="item">
<xsl:variable name="tmp"> <xsl:value-of select="."/></xsl:variable>
<xsl:if test="boolean(normalize-space($tmp))">
<TR><TD><xsl:value-of select="$tmp"/></TD></TR>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

     HTML 1     HOME     XML     XSL 1     OUTPUT 1     
<HTML>
<HEAD> </HEAD>
<BODY>
<TABLE BORDER="1">
<TR>
<TD> item 1 </TD></TR>
<TR>
<TD> item 2 </TD></TR>
<TR>
<TD> item 3</TD></TR></TABLE> </BODY> </HTML>

     OUTPUT 1     HOME     XML     XSL 1     HTML 1     
item 1
item 2
item 3

     XSL 2     HOME     XML     HTML 2     OUTPUT 2     
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' >
<xsl:template match="table">
<TABLE BORDER='1'>
<xsl:for-each select="item">
<xsl:apply-templates select="."/>
</xsl:for-each>
</TABLE>
</xsl:template>
<xsl:template match="item">
<TR><TD><xsl:value-of select="."/></TD></TR>
</xsl:template>
</xsl:stylesheet>

     HTML 2     HOME     XML     XSL 2     OUTPUT 2     
<HTML>
<HEAD> </HEAD>
<BODY>
<TABLE BORDER="1">
<TR>
<TD> item 1 </TD></TR>
<TR>
<TD> item 2 </TD></TR>
<TR>
<TD/></TR>
<TR>
<TD> </TD></TR>
<TR>
<TD> item 3</TD></TR></TABLE> </BODY> </HTML>

     OUTPUT 2     HOME     XML     XSL 2     HTML 2     
item 1
item 2
item 3