XML is an important part of web application in java. XML increase the capability of the java application and it makes more useful for application. Using XML with JSP with good XML tools is more easier to use in application. XML increase the value and flexibility of the application. Before starting XML, you should understand the XML. XML is Extensible Markup language and recommended by W3C.
XML gives the data in tree node logical structure.
DOM parser is used to handle with XML in java. DOM is Document Object Model which handle whole document and easy to use in application. DOM read the whole XML as document and keep in memory. Node can be accessed by Elements through getNodeValue() method.
Reading XML in java is easier from XML file. We will give an example to read xml file in java which explain about getting node value from XML. We are using JSP to read XML and using DOM Parser.
books.xml
<?xml version="1.0" encoding="iso-8859-1"?> <library> <book> <name>Head First Java, 2nd Edition</name> <author>Kathy Sierra and Bert Bates</author> <publication-date>09-Feb-2005</publication-date> </book> <book> <name>Effective Java</name> <author>Joshua Bloch</author> <publication-date>28-May-2008</publication-date> </book> <book> <name>Java How to Program, 7th Edition</name> <author>Harvey M. Deitel and Paul J. Deitel</author> <publication-date>6-Jan-2007</publication-date> </book> </library>
readDOMXML.jsp
<%@ page language="java" %> <%@ page import="org.w3c.dom.*" %> <%@ page import="javax.xml.parsers.DocumentBuilder" %> <%@ page import="javax.xml.parsers.DocumentBuilderFactory" %> <% DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db =dbf.newDocumentBuilder(); Document doc=db.parse("c:\\books.xml"); NodeList nl = doc.getElementsByTagName("book"); %> <html> <head> <title>How to read XML file in JAVA</title> </head> <body> <% for(int i=0;i<nl.getLength();i++) { NodeList nameNlc= doc.getElementsByTagName("name"); Element nameElements=(Element)nameNlc.item(i); String nameTagValue=nameElements.getChildNodes().item(0).getNodeValue(); NodeList authorNlc= doc.getElementsByTagName("author"); Element authorElements=(Element)authorNlc.item(i); String authorTagValue=authorElements.getChildNodes().item(0).getNodeValue(); NodeList dateNlc= doc.getElementsByTagName("publication-date"); Element dateElements=(Element)dateNlc.item(i); String dateTagValue=dateElements.getChildNodes().item(0).getNodeValue(); out.println("name :"+nameTagValue+"<br>"); out.println("author :"+authorTagValue+"<br>"); out.println("publication-date :"+dateTagValue+"<br><br>"); } %> </body> </html>





Link to Us