XML Parser using jsp

Author: satz | Date: September 7, 2009

Learn how to parse an XML file and load dynamic data into a jsp page. This tutorial is on the DOM parser in JSP.  The parser loads the xml data into a jsp page using the DOM parser.

Step1

Create an XML file.  You may do so by copying the following code into a bank XML page.

<?xml version="1.0" encoding="ISO-8859-1"?>
 <all>
 <title>FREE Tutorials on Web development scripts &amp; tools at www.tutorials2learn.com</title>
 <desc>Tutorials2learn is a FREE resource gallery. Our topics include articles for beginners, intermediate and for the advanced learners. We hope that, this will help us to build a very rich resource gallery, by mutual sharing of knowledge.</desc>
 <url>http://www.tutorials2learn.com/</url>
 </all>

Now, name the file as “data.xml”. The XML file is ready and now let’s look into the jsp parser.

Step.2

Create a new jsp page and name it as “myxmlparser.jsp”. Put the following code into it.

<%@ page import="javax.xml.parsers.*,org.w3c.dom.*" %>
 <%
 try{
 String XmlPath = "data.xml";
 %>
 <%!
 Document doc;
 String getXMLValue(String name) {
 NodeList nlist=doc.getElementsByTagName(name);
 String value = nlist.item(0).getFirstChild().getNodeValue();
 return value;
 }
 %>
 <%
 String appPath = application.getRealPath("/");
 DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
 DocumentBuilder db=dbf.newDocumentBuilder();
 doc=db.parse(appPath + XmlPath);
 String TitleVar    = getXMLValue("title");
 String DescVar    = getXMLValue("desc");
 String UrlVar    = getXMLValue("url");
 %>
 <h2><%=TitleVar%></h2>
 <p><%=DescVar%></p>
 <a href="<%=UrlVar%>" >Visit the Site</a>
 <%
 }catch(Exception e){
 }%>

Code Explained:

<%@ page import="javax.xml.parsers.*,org.w3c.dom.*" %>

Importing the necessary parsing classes.

String XmlPath = "data.xml";

Path to the Xml file.

<%!
 Document doc;
 String getXMLValue(String name) {
 NodeList nlist=doc.getElementsByTagName(name);
 String value = nlist.item(0).getFirstChild().getNodeValue();
 return value;
 }
 %>

Function to retrieve data from the  XML DOM.

String appPath = application.getRealPath("/");

get the real Path to the root in a variable.

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
 DocumentBuilder db=dbf.newDocumentBuilder();
 doc=db.parse(appPath + XmlPath);

XML DOM creation and parsing the XML. The DOM is ready for Communication with XML.

String TitleVar    = getXMLValue("title");
 String DescVar    = getXMLValue("desc");
 String UrlVar    = getXMLValue("url");

Get the node values into String variables.

<h2><%=TitleVar%></h2>
 <p><%=DescVar%></p>
 <a href=”<%=UrlVar%>” >Visit the Site</a>

Print the variable values into the page.

Click here to download the resorces.