JSTL XML Tag x:if Example
- Details
- Written by Nam Ha Minh
- Last Updated on 01 September 2019   |   Print Email
This post guides you how to use the <x:if> tag in the JSTL XML tags library with code example.
You know, the <x:if> is the XML conditional tag which evaluates the body of the tag if the given XPath expression evaluates to ‘true’.
JSTL <x:if> Syntax:
<x:if
select="<string>"
var="<string>"
scope="<string>">
...
</x:if>
Attributes:
Name | Required | Description |
select | True | XPath expression which determines whether body content is executed or not. If test evaluates to true body content is processed. |
var | False | Name of the variable which holds the result of the test condition. The type of this variable is Boolean. |
scope | False | Scope of the var. |
JSTL <x:if> Example:
The following JSP example displays the nodes with salary more than 10000. Note that there is no 'else' construct.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title><x:if> Demo</title> </head> <body> <h1><x:if> Demo</h1> <c:import url="http://localhost:8080/JSTL-Tag-Reference/tag-types/xml/citizens.xml" var="citizenXML"/> <x:parse var="doc" xml="${citizenXML}" /> <table border="1"> <x:forEach var="citizen" select="$doc/citizens/citizen"> <tr> <x:if select="salary>10000"> <td><x:out select="ssn" /></td> <td><x:out select="firstname" /></td> <td><x:out select="lastname" /></td> <td><b><x:out select="role" /></b></td> <td><b><x:out select="salary"/></b></td> </x:if> </tr> </x:forEach> </table> </body> </html>
XML Document (given for reference)
<?xml version='1.0' encoding='UTF-8' standalone='no'?> <citizens> <citizen> <ssn>Z345T</ssn> <firstname>Cheryl</firstname> <lastname>Johnson</lastname> <role>Manager</role> <salary>12000</salary> </citizen> <citizen> <ssn>Z446T</ssn> <firstname>John</firstname> <lastname>Smith</lastname> <role>Employee</role> <salary>1000</salary> </citizen> <citizen> <ssn>Z335T</ssn> <firstname>Justin</firstname> <lastname>Claire</lastname> <role>Senior Manager</role> <salary>14000</salary> </citizen> <citizen> <ssn>Z389T</ssn> <firstname>Clark</firstname> <lastname>Rick</lastname> <role>Employee</role> <salary>2000</salary> </citizen> </citizens>
Output:
Recommended Usage of <x:if> tag:
Particularly useful if we have only one condition to evaluate and we do not need to evaluate else conditions.
Other JSTL XML Tags:
forEach | out | param | parse | set | transform | choose, when, otherwise
Comments