There are many way how to read xml file. But i will show you how to read xml file using DOM xml Parser. DOM will parser the entire XML document and load into memory.
Since DOM will load XML document into memory, it will cost performance of the system if the xml document contains lot of data. Please consider SAX parser as solution if you have lot of data in xml document.
XML file example
this will be example of xml document.<?xml version="1.0" encoding="UTF-8"?> <domparsersys> <web-page id="001"> <page-name>index.jsp</page-name> <roles>*</roles> </web-page> <web-page id="002"> <page-name>usermanager.jsp</page-name> <roles>ADMINISTRATOR</roles> </web-page> </domparsersys>
JSP file
<%@page import="org.w3c.dom.Element"%> <%@page import="org.w3c.dom.Node"%> <%@page import="org.w3c.dom.NodeList"%> <%@page import="org.w3c.dom.Document"%> <%@page import="javax.xml.parsers.DocumentBuilder"%> <%@page import="javax.xml.parsers.DocumentBuilderFactory"%> <%@page import="java.io.File"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <h1>Read Xml using DOM parser</h1> <% try { File xmlFile = new File("D:/Data/example1.xml"); DocumentBuilderFactory docBuilderFac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFac.newDocumentBuilder(); Document doc = docBuilder.parse(xmlFile); //optional, but //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("web-page"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("<br/>Current Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; out.println("<br/>Page id : " + eElement.getAttribute("id")); out.println("<br/>Page Name : " + eElement.getElementsByTagName("page-name").item(0).getTextContent()); out.println("<br/>Roles : " + eElement.getElementsByTagName("roles").item(0).getTextContent()); } } } catch (Exception ex){ out.println(ex.getMessage()); } %> </body> </html>
Output
Page id : 001 Page Name : index.jsp Roles : * Page id : 002 Page Name : usermanager.jsp Roles : ADMINISTRATOR
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
0 comments:
Post a Comment