Magazine
 
Tips & Tricks
 
ReadMyXMLFile.java

import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class ReadMyXMLFile {
public static void main(String args[]) {
try {
File file = new File(“c:\\EmpInfo.xml”);

// Obtain a new instance of a DocumentBuilderFactory.

DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();

// Get the DocumentBuilder

DocumentBuilder db = dbf.newDocumentBuilder();

// Parse the content of the given file as an XML document.

Document doc = db.parse(file);

// Get a NodeList of all the Elements with tag name “Employee”.

NodeList EmpList =
doc.getElementsByTagName(“Employee”);

// Get the number of nodes i.e.
“Employee” in the list.

System.out.println(“\n* This file has record of “+ EmpList.getLength()+ “ employees.\n”);
System.out.println(“Employee Information List”);
System.out.println(“———————————— ”);
for (int index = 0; index < EmpList.getLength(); index++) {

// Go to the indexth item

Node node = EmpList.item(index);
// Check whether the node is an
Element. if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;

// Get a NodeList of all descendant Elements with tag name “Emp_Id”
NodeList EIDElmntLst =
element.getElementsByTagName(“Emp_Id”);
Element EIDElmnt = (Element)
EIDElmntLst.item(0);
NodeList EID =

 

EIDElmnt.getChildNodes();
System.out.println(“Emp ID : “ + ((Node)
EID.item(0)).getNodeValue());

// Get a NodeList of all descendant Elements with tag name “Emp_Name”

NodeList ENameElmntLst =
element.getElementsByTagName(“Emp_Name”);
Element ENameElmnt = (Element)
ENameElmntLst.item(0);
NodeList EName =
ENameElmnt.getChildNodes();
System.out.println(“Emp Name : “ +
((Node) EName.item(0)).getNodeValue());

// Get a NodeList of all descendant

Elements with tag name “Emp_E-mail”
NodeList EEmailElmntLst =
element.getElementsByTagName(“Emp_Email”);
Element EEmailElmnt = (Element)
EEmailElmntLst.item(0);
NodeList EEmail = EEmailElmnt.getChildNodes();
System.out.println(“Emp mail id : “ + ((Node)
EEmail.item(0)).getNodeValue()+”\n”);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}

The output of the above program is given below:



Dec 2007 | Java Jazz Up | 74
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 ,

Download PDF