To Count XML Element

In this section, you will learn to count the elements
present in a XML file using DOM APIs.
Description of program:
This program helps to count the XML
element. It takes a xml file (as a string ) at the console and checks its
availability. It parses the xml document using the parse() method.
After parsing the XML document it asks for element name which have to count.
Create a NodeList and use the getElementByTagName()
method. The getLength() method counts the occurrences of the specified
element. If the asked element is not available( i.e.. the given
element isn't found) it returns 0.
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> 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_E-mail>
</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> |
Here is the Java File: DOMCountElement.java
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class DOMCountElement{
public static void main(String[] args) {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse(xmlFile);
System.out.print("Enter element name: ");
String element = bf.readLine();
NodeList nodes = doc.getElementsByTagName(element);
System.out.println("xml Document Contains " + nodes.getLength() + " elements.");
}
else{
System.out.print("File not found!");
}
}
catch (Exception ex) {
System.out.println(ex);
}
}
}
|
Download this example.
Output of program:
C:\vinod\xml>javac DOMCountElement.java
C:\vinod\xml>java DOMCountElement
Enter File name: Employee-Detail.xml
Enter element name: Emp_Name
xml Document Contains 3 elements. |

|