Java xml count occurrence of elements


 

Java xml count occurrence of elements

In this section you will learn how to count the occurrence of xml 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:

<Person>
<Name>AAAA</Name>
<Address>Delhi</Address>
<Email>[email protected]</Email>

<Name>BBBB</Name>
<Address>Mumbai</Address>
<Email>[email protected]</Email>

<Name>CCCC</Name>
<Address>Kolkata</Address>
</Person>

Here is the code:

import java.io.*;
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.in));
		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();
						count++;
						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) {
			e.printStackTrace();
		}
	}
}

Output:

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

Ads