Processing XML with Java Published: July 24, 2007 PrintEmail
Parsing XML with SAX Package org.xml.sax Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing. SAX, the Simple API for XML, is a standard interface for event-based XML parsing, developed collaboratively by the members of the XML-DEV mailing list, currently hosted by OASIS
The first step in parsing an XML document with SAX is to obtain a SAX parser.The code looks like this:
The SAXParser class is a simple wrapper around the org.xml.sax.XMLReader class. Once you have obtained one, you can parse a document by simply calling one of the various parse() methods.
The following code shows a method that uses SAX to parse an XML file
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import java.io.File; public class SampleSAX { public static void main(String[] args) { ProductEventHandler handler= new ProductEventHandler(); try { SAXParserFactory factory= SAXParserFactory.newInstance(); SAXParser parser= factory.newSAXParser(); File ourExample= new File("products.xml"); parser.parse( ourExample, handler); } catch (Exception e) { System.out.println(e.getMessage()); } } }