I'm trying to parse XML file with SAX following this tutorial on Maven project. Here's my SAXLocalNameCount
:
public class SAXLocalNameCount extends DefaultHandler {
private static String filename = ".\\file.xml";
public static void main(String[] args) throws ParserConfigurationException, org.xml.sax.SAXException, IOException, SAXException {
SAXParserFactory spfactory = SAXParserFactory.newInstance();
spfactory.setNamespaceAware(true);
SAXParser saxParser = spfactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new SAXLocalNameCount());
xmlReader.parse(convertToFileURL());
}
private static void usage() {
System.err.println("Usage: SAXLocalNameCount <file.xml>");
System.err.println(" -usage or -help = this message");
System.exit(1);
}
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 = localName;
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);
System.out.println("Local Name \"" + tag + "\" occurs "
+ count + " times");
}
}
private static String convertToFileURL() {
String path = new File(filename).getAbsolutePath();
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
if (!path.startsWith("/")) {
path = "/" + path;
}
return "file:" + path;
}
}
This line:
XMLReader xmlReader = saxParser.getXMLReader();
gives me error:
ClassCastException: org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser cannot be cast to jdk.internal.org.xml.sax.XMLReader
What am I missing here?
My problem was that I was importing from jdk.internal.org.xml.sax.helpers.DefaultHandler and the right import was supposed to be org.xml.sax.helpers.DefaultHandler