Sunday, November 20, 2011

Simple SAX parser example (count number of elements in an xml file)


Example Xml File :



<?xml version = "1.0" ?>

<Employees>



<Employee>

<Emp_Id> 1 </Emp_Id>

<Emp_Name> Bob </Emp_Name>

<Emp_E-mail> bob@hotmail.com </Emp_E-mail>

</Employee>



<Employee>

<Emp_Id> 2 </Emp_Id>

<Emp_Name> Nick </Emp_Name>

<Emp_E-mail> nick@yahoo.com </Emp_E-mail>

</Employee>



<Employee>

<Emp_Id> 3 </Emp_Id>

<Emp_Name> John </Emp_Name>

<Emp_E-mail> john@gmail.com </Emp_E-mail>

</Employee>



</Employees>

Java code to parse the above xml file and provides the elements count

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class ElementCount{
int startTag = 0;
public static String ele;
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();
File file = new File(xmlFile);
if (file.exists()){
System.out.print("Enter tag name for which the count should be calculated:");
ele = bf.readLine();
ElementCount tagCount = new ElementCount(xmlFile);
}
else{
System.out.println("File not found!");
}
}
public ElementCount(String str){
try{
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
DefaultHandler dHandler = new DefaultHandler(){
public void startElement(String uri, String name, String element,
Attributes atri)throws SAXException{
if (element.equals(ele)){
startTag++;
}
}
public void endDocument(){
System.out.println("Total elements: " + startTag);
}
};
parser.parse(str,dHandler);
}
catch (Exception e){
e.printStackTrace();
}
}
}

Stumble
Delicious
Technorati
Twitter

0 Comments:

Post a Comment