
Hi.... if the XML file is small and repetitive then this will have meaning.. import javax.xml.parsers.; import org.xml.sax.; import org.xml.sax.helpers.; import java.io.;
public class SAXElementCount{
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 XML tag name:");
ele = bf.readLine();
SAXElementCount tagCount = new SAXElementCount(xmlFile);
}
else{
System.out.println("File not found!");
}
}
public SAXElementCount(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();
}
}
}
..
What if the xml file is very big or huge file? and sometimes we wont be aware of type of xml file...

Here is a code that parse xml file using dom parser in java.
import org.w3c.dom.*;
import org.w3c.dom.Node;
import javax.xml.parsers.*;
public class ParseXML{
public static boolean isTextNode(Node n){
return n.getNodeName().equals("#text");
}
public static void main(String[]args)throws Exception{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("c:/file.xml");
Element element = doc.getDocumentElement();
NodeList personNodes = element.getChildNodes();
for(int i=0; i<personNodes.getLength(); i++){
Node emp = personNodes.item(i);
if(isTextNode(emp))
continue;
NodeList nlist = emp.getChildNodes();
for(int j=0; j<nlist.getLength(); j++ ){
Node node = nlist.item(j);
if(isTextNode(node))
continue;
System.out.print(node.getFirstChild().getNodeValue()+"\t ");
}
System.out.println();
}
}
}

I need to parse using sax parser... i wanna use direct file path... not by defining each and every element..
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.