Parsing The XML File using DOM parser in JSP

W3C (World Wide Web Consortium) started the DOM (Document Object Model) parser, that is the platform independent and language-neutral interface.

Parsing The XML File using DOM parser in JSP

Parsing The XML File using DOM parser in JSP

     

W3C (World Wide Web Consortium) started the DOM (Document Object Model) parser, that is the platform independent and language-neutral interface. Programs can dynamically manipulate the content, structure and style of documents. The document is processed and the results after the processing are displayed on to the present page. DOM parser is not an ideal technology for JSP because JSTL (Java Server Pages Standard Tag Library) also provides actions for parsing an XML document.

This example helps you to parsing the xml page in jsp. 'parsingxml.jsp' uses 'roseindia.xml' file and display its content to the jsp page.

roseindia.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<roseindia>

  <employee>
  <name>Sandeep Kumar Suman</name>
  <date-of-birth>15-02-84</date-of-birth>
  <city>Gorakhpur</city>
  </employee>

  <employee>
  <name>Amit Raghuvanshi</name>
  <date-of-birth>19-12-86</date-of-birth>
  <city>Lucknow</city>
  </employee>

  <employee>
  <name>Vineet Bansal</name>
  <date-of-birth>05-02-83</date-of-birth>
  <city>Sonipat</city>
  </employee>

  <employee>
  <name>Vikas Singh</name>
  <date-of-birth>05-12-88</date-of-birth>
  <city>Hazipur</city>
  </employee>

  <employee>
  <name>Anusmita Singh</name>
  <date-of-birth>28-12-84</date-of-birth>
  <city>Bareilly</city>
  </employee>

</roseindia>

parsingxml.jsp

<%@page import="org.w3c.dom.*, javax.xml.parsers.*" %>
<%
  DocumentBuilderFactory docFactory = 
  DocumentBuilderFactory.newInstance
();
  DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
  Document doc = docBuilder.parse
(
"http://localhost:8080/ServletExample/roseindia.xml");
%>
<%!
  public boolean isTextNode(Node n){
  return n.getNodeName().equals("#text");
  }
%>
<html>
  <head><title>Parsing of xml using DOM Parser</title></head>
  <body>  
  <h2><font color='green'>Employees of Roseindia</font></h2>
  <table border="2">
  <tr>
  <th>Name of Employee</th>
  <th>Date of Birth</th>
  <th>City</th>
  </tr>
  <%
  Element  element = doc.getDocumentElement()
  NodeList personNodes = element.getChildNodes()
  for (int i=0; i<personNodes.getLength(); i++){
  Node emp = personNodes.item(i);
  if (isTextNode(emp))
  continue;
  NodeList NameDOBCity = emp.getChildNodes()
  %>
  <tr>
  <%
  for (int j=0; j<NameDOBCity.getLength(); j++ ){
  Node node = NameDOBCity.item(j);
  if isTextNode(node)) 
  continue;
  %>
  <td><%= node.getFirstChild().getNodeValue() %></td>
  <%
  
  %>
  </tr>
  <%
  }
  %>
  </table>
  </body>
</html>

Running The program on this url: http://localhost:8080/ServletExample/jsp/parsingxml.jsp  the following output will be generated.

Download Source Code