Get Data From the XML File
Here you will learn to retrieve data from XML file using SAX parser. We use the JAXP APIs to retrieve data from XML document .
Description of program:
In this example you need a well-formed XML file that has some data (Emp_Id, Emp_Name and Emp_E-mail in our case). Create a java program (EmployeeDetails.java) that retrieves data from it. When you run the program it asks for a file with a message "Enter XML file name:" at the command line and checks its existence through exists() method. If the given file exits, the instance of SAXParser class parses the file using the parse() method. Till the startElement() method returns 'true', the characters() method prints data . If the file doesn't exist it will display a message "File not found!".
Characters(char[] ch, int start, int len) method retrieves identification of character data. The Parser calls this method and to report every character data encountered . If any error occurs it throws the SAXException. This method takes the following parameters:
ch:
This is the characters of XML document.
start: This is staring position
in an array.
len: This is the number of
characters to read from an array.
Here is the XML File: Employee-Detail.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> |
Here is the Java File: EmployeeDetails.java
import javax.xml.parsers.*;
|
Output of program:
C:\vinod\xml\comXML>javac EmployeeDetails.java C:\vinod\xml\comXML>java EmployeeDetails Enter XML file name:Employee-Detail.xml XML Data: Emp_Id: E-001 Name: Vinod E-mail: [email protected] Emp_Id: E-002 Name: Amit E-mail: [email protected] Emp_Id: E-003 Name: Deepak E-mail: [email protected] |