001package edu.pdx.cs410J.xml;
002
003import java.io.*;
004import javax.xml.parsers.*;
005import org.xml.sax.*;
006import org.xml.sax.helpers.DefaultHandler;
007
008/**
009 * This program demonstrates the SAX parsing API by parsing a
010 * phonebook XML document and printing out the phone numbers in it.
011 */
012public class PrintPhoneNumbers extends DefaultHandler {
013  private static PrintStream out = System.out;
014  private static PrintStream err = System.err;
015
016  /**
017   * When we see a "phone" element, print out the area code and phone
018   * number
019   */
020  public void startElement(String namespaceURI, String localName,
021                           String qName, Attributes attrs)
022    throws SAXException {
023
024    if (qName.equals("phone")) {
025      String area = attrs.getValue("areacode");
026      String number = attrs.getValue("number");
027      out.println("(" + area + ") " + number);
028    }
029  }
030
031  public void warning(SAXParseException ex) {
032    err.println("WARNING: " + ex);
033  }
034
035  public void error(SAXParseException ex) {
036    err.println("ERROR: " + ex);
037  }
038
039  public void fatalError(SAXParseException ex) {
040    err.println("FATAL: " + ex);
041  }
042
043  /**
044   * Parses an XML file using SAX with an instance of this class used
045   * for callbacks
046   */
047  public static void main(String[] args) {
048    SAXParserFactory factory = SAXParserFactory.newInstance();
049    factory.setValidating(true);
050
051    SAXParser parser = null;
052    try {
053      parser = factory.newSAXParser();
054
055    } catch (ParserConfigurationException ex) {
056      ex.printStackTrace(System.err);
057      System.exit(1);
058
059    } catch (SAXException ex) {
060      ex.printStackTrace(System.err);
061      System.exit(1);
062    }
063
064    DefaultHandler handler = new PrintPhoneNumbers();
065    try {
066      File file = new File(args[0]);
067
068      InputSource source = new InputSource(new FileReader(file));
069      source.setSystemId(file.toURL().toString());
070      parser.parse(source, handler);
071
072    } catch (SAXException ex) {
073      ex.printStackTrace(System.err);
074      System.exit(1);
075
076    } catch (IOException ex) {
077      ex.printStackTrace(System.err);
078      System.exit(1);
079    }
080  }
081
082}