XSLT <xsl:if> Element
We can put a conditional test against the content of the XML file, using the <xsl:if> element.
The <xsl:if> Element:
In the XSL document, we can add an <xsl:if> element, to put a conditional if test against the content of the XML file.
Syntax:
<xsl:if test="expression"> ...Code if the expression is true... </xsl:if> |
Where to use the <xsl:if> Element:
In the XSL file, we need to add the <xsl:if> element inside the <xsl:for-each> element, to add a conditional test. The expression to be evaluated is included in the value of the required test attribute.
Example:
Books.xml:
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="Child"> <title lang="en">ABC</title> <author>Author Name</author> <year>2020</year> <price>100.00</price> </book> <book category="IT"> <title lang="en">XQuery Book</title> <author>Author 1</author> <author>Author 2</author> <year>2005</year> <price>300.00</price> </book> <book category="Sociology"> <title lang="en">Sociology 1</title> <author>Author Name</author> <year>2015</year> <price>250.00</price> </book> <book category="GK"> <title lang="en">Current Affairs</title> <author>Author Name</author> <year>2002</year> <price>500.00</price> </book> <book category="Science"> <title lang="en">Science Book</title> <author>Author 1</author> <author>Author 2</author> <author>Author 3</author> <year>2019</year> <price>150.00</price> </book> </bookstore> |
XSLT Code:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>List of Books</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Price</th> <th>Year</th> </tr> <xsl:for-each select="bookstore/book"> <xsl:if test="year>2005"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="price"/></td> <td><xsl:value-of select="year"/></td> </tr> </xsl:if> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> |
Output:
Explanation:
In the above example, only the title and price elements of the books with the year value higher than 2005 will be displayed.
Please Share