XML Parsing with SAX

Back | Home | Next

SAX, the Simple API for XML, is a standard interface for event-based XML parsing. The SAX API provides implemented interfaces for many different XML parsers. Metacat requires a SAX2 API/Java1.2 with any SAX2-compatible XML parser.

To avoid tying Metacat to any specific SAX parser, XMLReaderFactory is used as the SAX interface to Metacat for easy plugability of parsers. The SAX parser used must be set in the Metacat Properties file.

The following is an example of instatiating a parser for Metacat.

  XMLReader parser = null;
  // Set up the SAX document handlers for parsing
  try {
      ContentHandler chandler   = new DBSAXHandler(conn, action, docid, user);
      EntityResolver dbresolver = new DBEntityResolver(conn, (DBSAXHandler)chandler);
      DTDHandler dtdhandler     = new DBDTDHandler(conn);

      // Get an instance of the parser
      MetacatUtil util = new MetacatUtil();
      // Get the class name of SAX driver from some XML parser like:
      // org.apache.xerces.parsers.SAXParser
      String parserName = util.getOption("saxparser");
      // Given a class name, this method attempts to load and instantiate the class as an XML reader
      parser = XMLReaderFactory.createXMLReader(parserName);

      // Turn off validation
      parser.setFeature("http://xml.org/sax/features/validation", false);
      
      parser.setProperty("http://xml.org/sax/properties/declaration-handler", chandler);
      parser.setProperty("http://xml.org/sax/properties/lexical-handler", chandler);

      // Set Handlers in the parser to receive XML parsing events
      parser.setContentHandler((ContentHandler)chandler);
      parser.setEntityResolver((EntityResolver)dbresolver);
      parser.setDTDHandler((DTDHandler)dtdhandler);
      parser.setErrorHandler((ErrorHandler)chandler);

  } catch (SAXException saxe) {
      throw saxe;
  }

  

Back | Home | Next