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.

test.xml

<bookstore>
 <book category="COOKING">
 <title lang="en">Everyday Italian</title>
 <author>Giada De Laurentiis</author>
 <year>2005</year>
 <price>30.00</price>
 </book>
 <book category="CHILDREN">
 <title lang="en">Harry Potter</title>
 <author>J K. Rowling</author>
 <year>2005</year>
 <price>29.99</price>
 </book>
 <book category="WEB">
 <title lang="en">Learning XML</title>
 <author>Erik T. Ray</author>
 <year>2003</year>
 <price>39.95</price>
 </book>
</bookstore>

displayXML.jsp

<%@ page contentType="text/html"%>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory,
javax.xml.parsers.DocumentBuilder,org.w3c.dom.*"
%>
<%
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");
%>
<html>
<body><center>
 <table width="500" border="0" cellspacing="0" cellpadding="0">
 <tr>
 <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>
 </tr>
 <tr>
 <%
 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>
 </tr>
 <%
 }
 %>
 </table>
 </center>
</body>
</html>

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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 182 other followers

%d bloggers like this: