this is more of a general xml question. I'm looking for the best 
(quickest) routine to parse an xml File and return the xml-stylesheet 
processing instruction value, or null if it does not exist. 

One way it seems would be to use the Xalan XPath API (so as not to load an 
external stylesheet), giving it a DOM Node and the XPath expression for 
processing-instruction(xml-stylesheet). Or use DOM directly. But if the 
Document could be huge, perhaps it's best to use SAX. (But how do you tell 
SAX "hey, I've found it, you can stop processing now?" -- do you have to 
throw an exception)?

Anyways, I wrote this code to do it, and would appreciate comment on the 
best way to solve this (rather simple) problem. [Seems a lot of code for 
what could be a single method, but I guess that's the nature of SAX].

--
package test.xml;

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;


public class ProcessingInstructionFinder extends DefaultHandler {
      private String data = null;
      private String instruction;
      
      public ProcessingInstructionFinder(String instruction) {
         this.instruction = instruction;
      }

      public String parse(File file) throws ParserConfigurationException, 
SAXException, IOException {
         SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
         saxParser.parse(file, this);
         
         return data;
      }
      
      public void processingInstruction(String target, String data) throws 
SAXException {
         if(target.equals(instruction)) this.data = data;
      }
      
      // for testing
      public static void main(String[] args) {
         if(args.length != 2) {
            System.out.println("Usage: java ProcessingInstructionFinder file 
instruction");
            System.exit(-1);
         }
         
         try {
            ProcessingInstructionFinder finder = new 
ProcessingInstructionFinder(args[1]);
            String value = finder.parse(new File(args[0]));
            System.out.println(args[1] + " => " + value);
         } catch(Throwable t) {
            t.printStackTrace(System.err);
         }
      }
}


Reply via email to