Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

To Count The Elements in a XML File

In this section, you will learn to count the element in XML document using DOM APIs defined in the org.apache.xerces.parsers.DOMParser package.

Ads

To Count The Elements in a XML File

     

In this section, you will learn to count the element in XML document using DOM APIs defined in the org.apache.xerces.parsers.DOMParser  package. Your classpath must  contain  xercesImpl.jar  and xml-apis.jar files  to run this program.
You can download it from Xerces

Description of program: This program takes a file name from the console and checks its availability. If the file exists then  DOMParser is created  using the org.apache.xerces.parsers.DOMParser package.This object parses the given XML document. It asks the element name and counts its occurence in the xml file. If the given element doesn't exist it displays the '0' element.

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: CountNodes.java

import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;

public class CountNodes{
  public static void main(String[] args) {
  try{
  BufferedReader bf = new BufferedReader(
 
new InputStreamReader(System.in));
  System.out.print("Enter file name: ");
  String str = bf.readLine();
  File file = new File(str);
  if (file.exists()){
  DOMParser parser = new DOMParser();
  parser.parse(str);
  Document doc = parser.getDocument();
  System.out.print("Enter element that have to count: ");
  String ele = bf.readLine();
  NodeList list = doc.getElementsByTagName(ele);
  System.out.println("Number of nodes: " + list.getLength());
  }
  else{
  System.out.println("File not found!");
  }
  }
  catch (Exception e){
  e.getMessage();
  }
  }
}

Download this example.

Output of program:

C:\vinod\xml>javac CountNodes.java

C:\vinod\xml>java CountNodes
Enter file name: Employee-Detail.xml
Enter element that have to count: Emp_Name
Number of nodes: 3

Advertisements

Ads
Share on Google+Share on Google+

To Count The Elements in a XML File

Posted on: June 2, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: To Count The Elements in a XML File  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads