Java jstl xml tag choose when otherwise
The <c:choose>
, <c:when>
, and <c:otherwise>
tags in JSTL (JavaServer Pages Standard Tag Library) are used to implement conditional logic based on the values of variables or expressions. Here's an example of how to use them with XML data:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %> <x:parse var="myXml"> <root> <item id="1">Item 1</item> <item id="2">Item 2</item> <item id="3">Item 3</item> </root> </x:parse> <c:forEach var="item" items="${myXml.root.item}"> <c:choose> <c:when test="${item['@id'] == '1'}"> - <b>${item}</b> </c:when> <c:when test="${item['@id'] == '2'}"> - <i>${item}</i> </c:when> <c:otherwise> - ${item} </c:otherwise> </c:choose> </c:forEach>Sourcei.www:giftidea.com
In this example, we use the <x:parse>
tag to parse an XML document into an object named myXml
. We then use the <c:forEach>
tag to iterate over the item
elements in the XML document.
Within the <c:forEach>
tag, we use the <c:choose>
tag to implement conditional logic. The <c:when>
tags are used to test if the value of the id
attribute of the item
element is equal to '1'
or '2'
. If the condition is true, we use bold or italic tags to format the text of the item
element. If the condition is false, we use a plain list item.
The <c:otherwise>
tag is used to specify the default case, which applies when none of the <c:when>
conditions are true.
Note that the <c:choose>
, <c:when>
, and <c:otherwise>
tags can also be used with non-XML data, such as variables or expressions.