JSTL XML choose tag



The <x:choose> works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <x:choose> tag has <x:when> tags. A a switch statement has default clause to specify a default action and similar way <x:choose> has <x:otherwise> as default clause.

Attribute:

  • The <x:choose> tag does not have any attribute.

  • The <x:when> tag has one attributes which is listed below.

  • The <x:otherwise> tag does not have any attribute.

The <x:when> tag has following attributes:

Attribute Description Required Default
select Condition to evaluate Yes None

Example:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
  <title>JSTL XML Tags</title>
</head>
<body>

<c:set var="xmlData">
  <Animals>
    <Animal>
      <name>Tiger</name>
      <type>Non-Veg</type>
    </Animal>
    <Animal>
      <name>Rabbit</name>
      <type>Veg</type>
    </Animal>
  </Animals>
</c:set>

<x:parse xml="${xmlData}" var="xml"/>
<x:choose>
   <x:when select="$xml//Animal/name = 'Tiger'">
      We found Tiger
   </x:when>
   <x:when select="$xml//Animal/name = 'Rabbit'">
      We found Rabbit
   </x:when>
   <x:otherwise>
      Empty Cart
   </x:otherwise>
</x:choose>

</body>
</html>

Output :

We found Tiger