Java Development
Articles
Processing XML with Java
Published: July 24, 2007
Print    Email


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:


import javax.xml.parsers.*;

SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(true);
parserFactory.setNamespaceAware(true);
SAXParser parser = parserFactory.newSAXParser();

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());
}
}
}



View Comments (0)
Latest Articles
Java Threads

Delete file using File.delete( ) method

Copying Files in Java

Downloading the Contents of a URL

Java FTP Source Code

Processing XML with Java

Generating Random Numbers

Java Lexical Structure

Serializing

Learning java
Latest Posts
Last news from Bahrain islands
Posted by ribrothetit

Please, help me
Posted by FthrOfIIIChlds

Beginners tutorial!
Posted by perz

Health and Beauty FOREVER
Posted by SKACTANDATE

buy xanax fergana
Posted by FleseeKip

Newsletter
Subscribe to our Newsletter!

Your Email: