Search code examples
javaxmlreturnxmlreader

Return Objects created while parsing an XML Document


So I want to read data from an xml file, I am now at a point where I have XMLReader and ContentHandler in place and when the endDocument() is fired I have "collected" all the data I need from the document.

But now it seems that I ran into a wall...

How do I return the collected data (from the ContentHandler) so that it can be used in my application?


Solution

  • You may create a List<T> in ContentHandler.

    public class MyTextHandler implements ContentHandler {
      ....
      private ArrayList<YourModel> list;
    
      public MyTextHandler() {
        list= new ArrayList<YourModel>();
      }
      public ArrayList<YourModel> getList() {
        return list;
      }
      ....
    }
    

    Obtain list from the Handler:

    MyTextHandler handler=new MyTextHandler();
    reader.setContentHandler(handler);
    InputSource is = new InputSource(filename);
    reader.parse(is);
    
    ArrayList<YourModel> list=handler.getList();