Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This example assumes the following class is already on your CLASSPATH:

Include Page
XML Example
XML Example

Here is an example of using SAX with Groovy:

Code Block

import javax.xml.parsers.SAXParserFactory
import org.xml.sax.helpers.DefaultHandler
import org.xml.sax.*

class RecordsHandler extends DefaultHandler {
    def messages = []
    def currentMessage
    def countryFlag = false
    void startElement(String ns, String localName, String qName, Attributes atts) {
        switch (qName) {
           case 'car':
               currentMessage = atts.getValue('make') + ' of '; break
           case 'country':
               countryFlag = true; break
           case 'record':
               currentMessage += atts.getValue('type') + ' record'; break
    void characters(char[] chars, int offset, int length) {
       if (countryFlag) {
           currentMessage += new String(chars, offset, length)
    void endElement(String ns, String localName, String qName) {
        switch (qName) {
           case 'car':
               messages << currentMessage; break
           case 'country':
               currentMessage += ' has a '; countryFlag = false; break

def handler = new RecordsHandler()
def reader = SAXParserFactory.newInstance().newSAXParser().xMLReaderXMLReader
def inputStream = new ByteArrayInputStream(XmlExamples.CAR_RECORDS.getBytes("UTF-8"))
reader.parse(new InputSource(inputStream))

assert handler.messages == [
    'Holden of Australia has a speed record',
    'Peel of Isle of Man has a size record',
    'Bugatti of France has a price record'