1

With the below code I want to return a array of data back from the SAX parser for each data inside the nodes. I have a array list which will keep the data under each leaf node. How do I use this data outside the handler or return it? -

public class ReadXMLFile {

   public static xmldataparser(String argv[]) {

    try {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {

    boolean burl = false;
    boolean bip = false;
    List<String> a = new ArrayList<String>();

    public void startElement(String uri, String localName,String qName, 
                Attributes attributes) throws SAXException {

        System.out.println("Start Element :" + qName);

        if (qName.equalsIgnoreCase("URL")) {
            burl = true;
        }

        if (qName.equalsIgnoreCase("IP")) {
            bip = true;
        }



    }

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

        System.out.println("End Element :" + qName);

    }

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

        if (burl) {
            System.out.println("URL : " + new String(ch, start, length));
            a.add(new String(ch, start, length));
            burl = false;
        }

        if (bip) {
            System.out.println("IP : " + new String(ch, start, length));
            bip = false;
            a.add(new String(ch, start, length));
        }


    }

     };
  }
return <the array from the handler(this is where I need help)>
 }
}

2 Answers 2

1

If you make the variables that store your result (e.g. a in this case) public or create a getter method for them, you will be able to access them and use any information stored there in code outside of the handler class.

Sign up to request clarification or add additional context in comments.

Comments

0

Create another class and extends DefaultHandler. Create method in handler class(ex:-sample). Before calling SAXParser.parse(filename,handler) make a call sample method. Create list as a global variable. You can add the required values to the list. Finally return the list from the sample method.

1 Comment

Please add some code and formatting to your answer - it is difficult to read. You can use a numbered list in your answer for better quality. Thank you for your contribution

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.