0

I will explain my design implementation of SAX parser through the following separate .java files.

Parser.java

public static void main(String[] args){
   Parser myParser = new Parser();
   Parser.parseXML(inputFile);  //may not be correct call, 
                             //but using it to make things clear to understand
}


public void parseXML(File inputFile) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser   parser = factory.newSAXParser(); 
        SaxHandler handler = new SaxHandler();
        parser.parse(inputFile, handler);
    } ....
}

SaxHandler.java

public class SaxHandler extends DefaultHandler {

public void startElement(String uri, String localName, 
                         String qName, Attributes attributes) throws SAXException{
    MyClass mine = new MyClass();
    return mine.returnString;  // I would like to have this line so that I can return               
                              //"Hello" ultimately to the main method
}

public void characters(char ch[], int start, int length) throws SAXException { 
}  

public void endElement(String uri, String localName,
                       String qName) throws SAXException {
}

MyClass.java

public String returnString()
{
    return "Hello";
}

As I mentioned in the comments, I want to find out a way or change my implementation so that I can get the String "Hello" in the main method. In the above implementation, the problem is with the return types of startELement and endELement methods of SAXHandler. Is there any workaround or design changes so that I can achieve the desired result? I hope my question is clear.

Thanks

2 Answers 2

1

The more general question behind it seems to be: how can the parser build up some data structure from what it is reading.

In your case you could store the data (i.e. "Hello") in a private field of SaxHandler. Further you add a getter, i.e. String getData() to SaxHandler. The method parseXml could then end with

  return handler.getData();
0

In the constructor of your SaxHandler you can get a reference to the Parser object, and call desired methods in Parser that would handle the string you want.

Returning in the middle of startElement is not correct because it would stop the entire parsing process. Therefore, all methods in DefaultHandler are void.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.