Woodstox : SAX Parsing Using Woodstox

Overview

SAX (Simple API for XML) is an event based parser. The XML document is accessed sequentially and elements of the XML file are handled using callback methods in SAX API.

In the following program, we’ll explore how Woodstox provides support for SAX parsing.

Create the XML file to be parsed as shown below. It describes the details of employee like his id, name and salary (see lines 2-4 below).

Create TestSaxParsing file as shown below.

Create and instance of
SAXParserFactory
by assigning
WstxSAXParserFactory
class (see line 18 below).

Create the
SAXParser
from the factory (see line 19 below).

Extend
DefaultHandler
class (see lines 21-72 below). The default handler contains the following callback methods:

  • startElement: callback method to handle start of XML element (see lines 27-44 below)
  • endElement: callback method to handle end of XML element (see lines 46-51 below)
  • characters: callback method to handle character content within element (see lines 53-70 below)

Load the XML file and start SAX parsing (see lines 73-74 below).

Define the main method (see lines 82-84 below) call doSaxParsing() method by passing the employee.xml file

The output of the program demonstrating SAX parsing is shown below:

Download Source Code for this Program

Leave a Reply

Your email address will not be published. Required fields are marked *