Search code examples
javaxmlparsingstoresax

How to store Data after SAX parsing


I use a SAX parser to parse an xml file and store my data into some arraylists-hashmaps within the endDocument method of the parser. It seems though that after parsing ends all my references are gone and when i try to access them from my main method i get zero arraylist-hashmap size(). In other words i save the data after parsing but can only print them out during the sax-parsing. How would it be possible to save them in order to re-use them after parsing is done? I have tried creating a list of Objects containing the information i need but it didnt work.

Handler code:

public class MyHandler extends DefaultHandler { 
private List<String> Rules = new ArrayList<String>();


public MyHandler() {acc = new StringBuilder();}  
public void startDocument(){

        String startDocumentString="Parsing started -----  Discovered Rules :";             
        System.out.println(startDocumentString);}

public void endDocument(){          
        String endDocumentString="\n \nParsing ended ------";               
        System.out.println(endDocumentString);
for(int i=0 ; i< rulesNumber ; i++){
setRules(Result[(0+(3*i))]);
System.out.println("Assosiative Rule " + (i+1) +": "+ Result[(0+(3*i))]);}

public void startElement(String nameSpaceURI, String localName, String qName, Attributes atts) {
if(qName.equals("AssociationRule")) {
setRulesNumber();}

public void endElement(String nameSpaceURI,String localName, String qName) {
(acc.toString()).trim();
    System.out.print(acc.toString());
    Results.add(acc.toString());        

    acc.setLength(0);
    unsetDecision();
    }           

public void characters (char[] ch, int start , int length) { 
    if(decision)
    acc.append(ch, start, length);          
    }


public void setRules(String s){Rules.add(s);}

public List<String> getRules(){return Rules;}   

Solution

  • You need to keep a reference to your ContentHandler e.g.

    //keep a reference to MyHandler
    MyHandler handler = new MyHandler();
    
    XMLReader parser = XMLReaderFactory.createXMLReader();
    
    parser.setContentHandler(handler);
    
    parser.parse(mySource);
    
    //get your results
    List<String> rules = handler.getRules();