/**
* Program to count the number of "tags" AKA elements in an XML document.
* This example also shows one way to turn on validation and how to use a
* SAX ErrorHandler.
*
* Notes: DefaultHandler is a SAX helper class that implements the SAX
* ContentHandler interface by providing no-op methods. This class
* overrides some of the methods by extending DefaultHandler.
*
*/
public class SAXTagCount extends DefaultHandler {
// A Hashtable with tag names as keys and Integers as values
private Hashtable tags;
// Parser calls this once at the beginning of a document
public void startDocument() throws SAXException {
tags = new Hashtable();
}
// Parser calls this for each element in a document
public void startElement(String namespaceURI, String localName,
String rawName, Attributes atts)
throws SAXException
{
String key = localName;
Object value = tags.get(key);
if (value == null) {
// Add a new entry
tags.put(key, new Integer(1));
} else {
// Get the current count and increment it
int count = ((Integer)value).intValue();
count++;
tags.put(key, new Integer(count));
}
}
// Parser calls this once after parsing a document
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 <" + tag + "> occurs " + count
+ " times");
}
}
/**
* Convert from a filename to a file URL.
*/
private static String convertToFileURL(String filename) {
// On JDK 1.2 and later, simplify this to:
// "path = file.toURL().toString()".
String path = new File(filename).getAbsolutePath();
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
if (!path.startsWith("/")) {
path = "/" + path;
}
return "file:" + path;
}
// Parse arguments
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-v")) {
validation = true;
} else {
filename = args[i];
// Must be last arg
if (i != args.length - 1) {
usage();
}
}
}
if (filename == null) {
usage();
}
// There are several ways to parse a document using SAX and JAXP.
// We show one approach here. The first step is to bootstrap a
// parser. There are two ways: one is to use only the SAX API, the
// other is to use the JAXP utility classes in the
// javax.xml.parsers package. We use the second approach here
// because it allows the application to use a platform default
// implementation without having to specify a system property.
// After bootstrapping a parser/XMLReader, there are several ways
// to begin a parse. In this example, we use the SAX API.
// Create a JAXP SAXParserFactory and configure it
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(validation);