How to iterate over nodes of XML in JSP?


The <x:forEach> tag is used to loop over nodes in an XML document.

Attribute

The <x:forEach> tag has the following attributes −

AttributeDescriptionRequiredDefault
selectThe XPath expression to be evaluatedYesNone
varName of the variable to store the current item for each loopNoNone
beginThe start index for the iterationNoNone
endThe end index for the iterationNoNone
stepThe size of the index increment while iterating over the collectionNoNone
varStatusThe name of the variable in which the status of the iteration is storedNoNone

Example

The following example shows the use of the <x:forEach> tag −

<%@ 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 x:if Tags</title>
   </head>
   <body>
      <h3>Books Info:</h3>
      <c:set var = "xmltext">
         <books>
            <book>
               <name>Padam History</name>
               <author>ZARA</author>
               <price>100</price>
            </book>
            <book>
               <name>Great Mistry</name>
               <author>NUHA</author>
               <price>2000</price>
            </book>
         </books>
      </c:set>
      <x:parse xml = "${xmltext}" var = "output"/>
      <ul class = "list">
         <x:forEach select = "$output/books/book/name" var = "item">
            <li>Book Name: <x:out select = "$item" /></li>
         </x:forEach>
      </ul>
   </body>
</html>

You will receive the following result −

Books Info:
Book Name: Padam History
Book Name: Great Mistry

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements