7. Setting conditions
The stylesheet that was discussed at the end of section 6 contains the following fragment:
From <xsl:value-of select="author"> to <xsl:value-of select="recipient"/><br/> <xsl:value-of select="place"/> <br/> <xsl:value-of select="year"/> <br/> <value-of select="callnumber"/> <br/>
According to the DTD on which this XML file is based, none of the elements within <letter>
are mandatory. It may be the case that certain elements are missing. What will happen when, for example, <place>
is missing? In the code above, it can be seen that a line break (<br/>
) is inserted after each <value-of>
element. If collection.xml is transformed with this stylesheet, there will be a slight problem with the second letter. Apparently, the place in which this letter was written could not be established. The stylesheet cannot select a value, and, since a line break is printed after each command (<br/>
), an empty line will be printed. This results in a somewhat confusing HTML code:
This problem can be solved by selecting certain elements only under a certain condition. To define a condition, use the element <xsl:if>
. This element must used with a test attribute specifying the condition. The instructions between the opening and closing tag of the <xsl:if>
element will be performed only if this condition can be evaluated as true.
Our current stylesheet can be improved by surrounding all the optional elements by <xsl:if>
, as follows:
... <xsl:if test="place"> <xsl:value-of select="place"/> </xsl:if> ...
This script only shows the contents of the <place>
element if this element is actually present.