to the main page about the tutorial  THE XML REVOLUTION  -  TECHNOLOGIES FOR THE FUTURE WEB back up next

A simple SAX example

The following Java programs reads the recipe collection and outputs the total amount of flour being used (assuming the unit is always cup):

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.apache.xerces.parsers.SAXParser;

public class Flour extends DefaultHandler {

  float amount = 0;

  public void startElement(String namespaceURI, String localName,
                           String qName, Attributes atts) {
    if (namespaceURI.equals("http://recipes.org") && localName.equals("ingredient")) {
       String n = atts.getValue("","name");
       if (n.equals("flour")) {
         String a = atts.getValue("","amount"); // assume 'amount' exists
         amount = amount + Float.valueOf(a).floatValue();
       }
    }
  }

  public static void main(String[] args) {
    Flour f = new Flour();
    SAXParser p = new SAXParser();
    p.setContentHandler(f);
    try { p.parse(args[0]); } 
    catch (Exception e) {e.printStackTrace();}
    System.out.println(f.amount);
  }
}

The output for our recipe collection is:

7.75

Only a tiny amount of the XML document is stored at any time.

back COPYRIGHT © 2000-2003 ANDERS MØLLER & MICHAEL I. SCHWARTZBACH next