|
Subject:
|
import org.xml.sax is deprecated
|
|
Posted By:
|
sax
|
Post Date:
|
11/10/2003 11:26:45 AM
|
Hi All, Please help ... I am a beginner of using SAX with Java. I think I don't have the org.xml.sax.* classes in my java class. So, I downloaded "saxjava-1.0" from www.megginson.com (I hope I downloaded the correct one). I unzipped the file and put it in my Java folder. However, it doesn't work when I run my Java code. I think I might missed out something ... like didn't import the file to Java classes? If so, how can I do that? My java code is trying to read an XML file and print out how many books in the xml file. After compiled, it has the following message:
"package com.jclark.xml.sax does not exists"
and 2 compiler warnings: C:\XML\BookCounter.java:12:warning:org.xml.sax.HandlerBase in org.xml.sax has been deprecated.
C:\XML\BookCounter.java:21:warning:org.xml.sax.Parser in org.xml.sax has been deprecated.
My java code as follow: ------------------------------ import org.xml.sax.*;
public class BookCounter extends HandlerBase { public static void main (String args[]) throws Exception { (new BookCounter()).countBooks(); } public void countBooks() throws Exception { Parser p = new com.jclark.xml.sax.Driver(); p.setDocumentHandler(this); p.parse("file:///C:/books.xml"); } } ------------------------------------
|
|
Reply By:
|
armmarti
|
Reply Date:
|
11/17/2003 7:35:45 AM
|
Hi,
it'll be better to separately define a Handler class.
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SimpleHandler extends DefaultHandler
{
public static int bookCount = 0;
public void startElement(String namespace, String localName, String qName, Attributes attributes) throws SAXException
{
if(localName.equals("book")) {
++bookCount;
}
}
}
Then you can test it like this:
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.ParserAdapter;
import java.io.IOException;
import org.xml.sax.SAXException;
public class TestSAX {
public static void main(String[] args)
{
XMLReader reader = null;
if(System.getProperty("org.xml.sax.parser") == null) {
System.setProperty("org.xml.sax.parser", "org.apache.xerces.parsers.SAXParser");
}
try {
reader = new ParserAdapter();
reader.setContentHandler(new SimpleHandler());
reader.parse("books.xml");
System.out.println("C = " + SimpleHandler.bookCount);
} catch (SAXException ex) {
ex.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
I've set Xerces as the default SAX parser, although you can set your preferred SAX parser through JVM parameter.
Regards, Armen
|