Share on Google+Share on Google+

Java xml count occurrence of elements

In this section you will learn how to count the occurrence of xml elements.

Java xml count occurrence of elements

Java provides xml parsers to read, update, create and manipulate an XML document in a standard way. You have used xml parsers for different purposes. Here we will count the number of occurrences of each element in an XML document using SAX Parser and display them. The document file to be processed should be identified through the command line argument.

Here is data.xml:

<Email>[email protected]</Email>

<Email>[email protected]</Email>


Here is the code:

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

public class CountElements {
	public static void main(String args[]) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(;
		System.out.print("Enter XML file name:");
		String xmlFile = bf.readLine();
		File file = new File(xmlFile);
		if (file.exists()) {
			CountElements tagCount = new CountElements(xmlFile);
		} else {
			System.out.println("File not found!");

	public CountElements(String str) {
		try {
			SAXParserFactory parserFact = SAXParserFactory.newInstance();
			SAXParser parser = parserFact.newSAXParser();
			DefaultHandler dHandler = new DefaultHandler() {
				private Hashtable tags;

				public void startDocument() throws SAXException {
					tags = new Hashtable();

				public void startElement(String namespaceURI, String localName,
						String qName, Attributes atts) throws SAXException {
					String key = qName;
					Object value = tags.get(key);
					if (value == null) {
						tags.put(key, new Integer(1));
					} else {
						int count = ((Integer) value).intValue();
						tags.put(key, new Integer(count));

				public void endDocument() throws SAXException {
					Enumeration e = tags.keys();
					while (e.hasMoreElements()) {
						String tag = (String) e.nextElement();
						int count = ((Integer) tags.get(tag)).intValue();
						System.out.println(tag + " occurs " + count + " times");
			parser.parse(str, dHandler);
		} catch (Exception e) {


Enter XML file name:c:/data.xml
Name occurs 3 times
Person occurs 1 times
Email occurs 2 times
Address occurs 3 times



Posted on: July 3, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null