Vishwakarma Institute of Technology, Pune-37.

Title

: Java Program for parsing XML file (convert XML objects to Java objects)

--------------------------------------------------------------------------------------------------------------------DOM.java import javax.xml.parsers.*; import java.io.*; import org.w3c.dom.*; public class DOM { public static void main(String[] args) { try { DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("Hostel.xml")); Element root = document.getDocumentElement(); System.out.println(root.getTagName()); System.out.println("Name:"+root.getAttribute("name")); System.out.println("Mission:"+root.getAttribute("mission")); /*NodeList n=root.getElementsByTagName("quality"); Node x=n[0]; Node y=n[0].childnodes[0]; String s=y.nodeValue();*/ //System.out.println(s); NodeList segments =root.getElementsByTagName("segment"); for(int i=0; i<segments.getLength(); i++) { Element segment = (Element)segments.item(i); System.out.println(segment.getTagName()); System.out.println("Segmentt Name:"+segment.getAttribute("name"));

Department of Computer Engineering

Vishwakarma Institute of Technology, Pune-37.

System.out.println("segment Mission:"+segment.getAttribute("mission")); } } catch(Exception e) { e.printStackTrace(); } } }

Wipro.XML <?xml version="1.0" encoding="UTF-8"?> <!-Document : Hostel.xml Created on : 18 November, 2011, 9:21 AM Author : DELL

Description: Purpose of the document follows. --> <Hostel name="Aboli girls hostel" mission="providing good facility ..."> <quality>good living style</quality> <Rector name="Ms.chavan" phone="410-778-1234"/> <Address name="Sukhsagar Nagar"> <street name="Katraj Road " blockno="60"/> </street> </Address> </Hostel>

Department of Computer Engineering

Vishwakarma Institute of Technology, Pune-37.

OUTPUT : init: deps-jar: compile-single: run-single: Hostel Name: Hostel Mission: providing good facility ... Address: Address Name: Pune street name=Katraj Road blockno=60 BUILD SUCCESSFUL (total time: 0 seconds)

Department of Computer Engineering

Sign up to vote on this title
UsefulNot useful