Magazine
 
XML- SAX Parser using JAXP API

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 full source code of

EmpSaxParser.java:

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
public class EmpSaxParser{
public static void main(String[] args) throws
IOException{
BufferedReader bf = new
BufferedReader(new
InputStreamReader(System.in));
System.out.print(“Enter XML file name:”);
String xmlFile = bf.readLine();
EmpSaxParser detail = new
EmpSaxParser(xmlFile);
}
public EmpSaxParser(String str){
try{
File file = new File(str);
if (file.exists()){
XMLReader reader =
XMLReaderFactory.createXMLReader();
reader.parse(str);
System.out.println(str + “ is wellformed
“);
System.out.println(“”);
SAXParserFactory parserFact =
SAXParserFactory.newInstance();
SAXParser parser =
parserFact.newSAXParser();
System.out.println(“XML Data: “);
DefaultHandler dHandler = new
DefaultHandler(){
boolean id;
boolean name;
boolean mail;

 

 
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);
}
else{
System.out.println(“File not found!”);
}
}
catch (SAXException sax){
System.out.println(str + “ isn’t wellformed”);
}
catch (Exception e){
System.out.println(“XML File hasn’t any
elements”);
e.printStackTrace();
}
}
}
XML- SAX Parser using JAXP API

 

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