Magazine
 
XML- SAX Parser using JAXP API
 

document using JAXP APIs.

Description of the 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). Here is the XML File to be parsed: Employee-
Detail.xml

<?xml version = “1.0” ?>
<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </
Emp_E-mail>
</Employee>
<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit </Emp_Name>
<Emp_E-mail> Amit2@yahoo.com </Emp_Email>
</Employee>
<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak </Emp_Name>
<Emp_E-mail> Deepak3@yahoo.com </
Emp_E-mail>
</Employee>
</Employee-Detail>

Develop a java file (EmpSaxParser.java) that uses an xml file to parse and check its wellformed ness. Initially the program checks that the given file exists or not by using exists() method. Here is a sample code of this program:

File file = new File(str); if (file.exists()){
XMLReader reader =
XMLReaderFactory.createXMLReader();
reader.parse(str);
System.out.println(str + “ is wellformed
“);

The XMLReaderFactory helps in creating an XML reader, which parses xml document using the appropriate callbacks. And it determines that the parsed xml is well-formed or not. If xml document is will-formed, it will display a message“Employee-Detail.xml is well-formed!” Otherwise

 

prints “Employee-Detail.xml isn’t well-formed!”. If you enter a file that doesn’t exist it will show “File not found!”.
Now, lets see the sample code to parse the data:

public void startElement(String uri,
String localName,
String element_name, Attributes
attributes)throws SAXException{
if (element_name.equals(“Emp_Id”)){
id = true;
}
if
(element_name.equals(“Emp_Name”)){
name = true;
}
if (element_name.equals(“Emp_Email”)){
mail = true;
}
}
public void characters(char[] ch, int start, int
len) throws SAXException{
String str = new String (ch, start,
len);
if (id){
System.out.println(“Emp_Id:
“+str);
id = false;
}
if (name){
System.out.println(“Name: “+str);
name = false;
}
if (mail){
System.out.println(“E-mail: “+str);
mail = false;
}
}
}

parser.parse(str, dHandler);

If the given file exits and well-formed then the instance of SAXParser class parses the file using the parse() method. As long as the startElement() method returns ‘true’, the characters() method prints data .

Feb  2008 | Java Jazz Up |28
 
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 ,

Download PDF