Ecco un mio esempio basilare:
codice:
import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class XmlSaxTester extends DefaultHandler
{
private File file;
public XmlSaxTester (String filename)
{
file = new File (filename);
}
public void load ()
throws SAXException, ParserConfigurationException, IOException
{
SAXParserFactory factory = SAXParserFactory.newInstance ();
SAXParser saxParser = factory.newSAXParser ();
saxParser.parse (file, this);
}
public void startDocument ()
throws SAXException
{
System.out.println ("Inizio del documento");
}
public void endDocument ()
throws SAXException
{
System.out.println ("Fine del documento");
}
public void startElement (String namespaceURI, String lName, String qName, Attributes attrs)
throws SAXException
{
System.out.println ("Inizio dell'elemento " + qName);
}
public void endElement (String namespaceURI, String lName, String qName)
throws SAXException
{
System.out.println ("Fine dell'elemento " + qName);
}
public void characters (char[] buf, int offset, int len)
throws SAXException
{
String s = new String (buf, offset, len);
System.out.println ("Caratteri \"" + s + "\"");
}
public static void main (String[] args)
{
if (args.length == 1)
{
try
{
XmlSaxTester tester = new XmlSaxTester (args[0]);
tester.load ();
}
catch (Exception e)
{
System.out.println (e);
}
}
else
{
System.out.println ("Usage: XmlSaxTester <xml file>");
}
}
}