Home Tutorial Java Xml Java xml count occurrence of elements

 
 

Share on Google+Share on Google+
Java xml count occurrence of elements
Posted on: July 3, 2010 at 12:00 AM
Advertisement
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>aa@roseindia.net</Email>

<Name>BBBB</Name>
<Address>Mumbai</Address>
<Email>bb@roseindia.net</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
Advertisement

Related Tags for Java xml count occurrence of elements:


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.

Posted on: July 3, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com