XSLT <if> Element
<xsl:if> element allows you to perform conditional statements against the contents of your XML document.
For example, you can present different content only if a given condition is met.
This element can be used in conjunction with the
<xsl:for-each> element to present different content depending on the contents of the XML file.
The Source File
Imagine have an XML file containing a list of food and it's nutritional value. Something like this:
Now, imagine we're only interested in the vegetables — we only want to display the food that have a type attribute of
vegetable. And, we also want to display it nicely formatted in an HTML table. Something like this:
To achieve the above outcome, we use
<xsl:for-each> to loop through each
food_item element, and
<xsl:if> to check the value of the
type attribute (we do this by using the
@ symbol — that's how you specify that it must be an attribute). If the attribute value equals
vegetable we output the details.