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:
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" ?>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit </Emp_Name>
<Emp_E-mail> Amit2@yahoo.com </Emp_E-mail>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak </Emp_Name>
<Emp_E-mail> Deepak3@yahoo.com </Emp_E-mail>
Here is the Java File: EmployeeDetails.java
Output of program:
Enter XML file name:Employee-Detail.xml
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial