XML Count Elements
Here providing you an example that counts the number of tags <Emp_Id> that are used in your XML document using the SAX parser.
Description of program:
Developing a java program, you need a XML well-formed document. When you run this program takes a xml file and checks it. If the given file exists, again it takes a tag name. Here we apply a parameterized constructor (SAXElementCount) that contains xml file. We define a default handler that implements for all SAX events and overrides two methods like: startElement() and endDocument(). The startElement method is called by parser each time. When this method overrides the code checks the given tag and counter is increased (startTag++). At last the parser reaches the end of document, the endDocument method is called and prints total number of elements. Any error occurred, exception has been thrown. If file doesn't exist it will display a message "File not found!".
Here is the XML File: Employee-Detail.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> |
Here is the Java File: SAXElementCount.java
import javax.xml.parsers.*;
|
Output of program:
C:\vinod\xml>javac SAXElementCount.java C:\vinod\xml>java SAXElementCount Enter XML file name:Employee-Detail.xml Enter XML tag name:Emp_Id Total elements: 3 |