Displaying XML data in JSP page

Here is an example in which XML content is accessed to display in JSP page.  We have XML file which contain some books data, which has been displayed in JSP in a table format.

In this example DocumentBuilderFactory class is used for factory API. Then DocumentBuilder type db is created to convert XML file to Document doc. Then each node has accessed in the NodeList and the value of each NodeList (nl) is printed using its indexes.


 <book category="COOKING">
 <title lang="en">Everyday Italian</title>
 <author>Giada De Laurentiis</author>
 <book category="CHILDREN">
 <title lang="en">Harry Potter</title>
 <author>J K. Rowling</author>
 <book category="WEB">
 <title lang="en">Learning XML</title>
 <author>Erik T. Ray</author>


<%@ page contentType="text/html"%>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory,
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("http://localhost:8080/practice/test.xml");

NodeList nl= doc.getElementsByTagName("title");
NodeList n2= doc.getElementsByTagName("author");
NodeList n3= doc.getElementsByTagName("year");
NodeList n4= doc.getElementsByTagName("price");
 <table width="500" border="0" cellspacing="0" cellpadding="0">
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Title</td>
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Author</td>
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Year</td>
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Price</td>
 for(int i=0;i<3;i++)
 <td><%= nl.item(i).getFirstChild().getNodeValue() %></td>
 <td><%= n2.item(i).getFirstChild().getNodeValue() %></td>
 <td><%= n3.item(i).getFirstChild().getNodeValue() %></td>
 <td><%= n4.item(i).getFirstChild().getNodeValue() %></td>

Actually I was trying to display these XML data by using loop. But I did not get any solution to read the total number of node in the XML file from JSP. So Readers, if you got any solution for my problem, please write me.