[jdom-interest] JDOM on the fly

Laurent Bihanic laurent.bihanic at atosorigin.com
Wed May 22 05:29:33 PDT 2002


Hi Dave,

You should have a look at ElementScanner (in package 
org.jdom.contrib.input.scanner in the jdom-contrib CVS module), it does just 
what you want.
Basically ElementScanner is a SAXFilter on which you register listeners 
associated to XPath-like expressions. When an element matches one of the 
registered XPath expressions, ElementScanner builds the element subtree, 
notifies the associated listener(s) and... forget about this element so that 
the garbage collector can free the memory.

With ElementScanner, your code will look like:
    ElementScanner f = new ElementScanner();
    f.addElementListener(myListener, "/doc/*");
    f.parse(new InputSource("test.xml"));

With myListener an instance of a class that implements ElementListener:
    public void elementMatched(String path, Element e) throws JDOMException {
       if (e.getName().equals("a")) {
          ...
       }
    }

Of course, you can choose to have one implementation of ElementListener for 
each type of element (a, b, c, ...) in which case you just have to register 
different listeners
    f.addElementListener(myListener1, "/doc/a");
    f.addElementListener(myListener2, "/doc/b");
    f.addElementListener(myListener3, "/doc/c");

ElementScanner is in sync with the latest JDOM so you'll get some problems if 
you're compiling against beta 8. You'll just have to add two or three throws 
clauses for IOEXceptions.

Hope this helps,

Laurent


Beleznay, Dave wrote:
> Hi there,
> 
> I'm trying to do something that might already exist, but I'm not really sure so I'm asking here.  
> 
> I'd like to take an xml document such as:
> 
> <doc>
>   <a/>
>   <a/>
>   <a/>
>   <b/>
>   <b/>
>   <b/>
>   <c/>
>   <c/>
> </doc>
> 
> and as the document is parsed with a sax parser,  make a jdom document (or element) for <a> and file it off to a handler,  make a jdom document for <b> and file it off to it's own handler, and similar for c (and d, e ....).  Basically,  I'd want something similar to,  
> 
>   Element ele = document.getRootElement();
>   Iterator i = v.iterator();
>   while (i.hasNext() )  {
>     Element ele2 = ele.getChild( (String)i.next()  );
>     if (ele.getName().equals("A")) {  
>       //do something
>     } else if (ele.getName().equals("B")) {
>       //do something else
>     }
>   }
> 
> but without putting the whole document in memory at once.  
> 
> So my question,  does something like this already exist?  I'm looking at extending SAXHandler, or org.xml.sax.helpers.DefaultHandler directly,  (is that the right direction even?) but i'm not sure if there is a faster way.
> 
> Thanks,
> 
> Dave
> 
> -------
> David Beleznay
> Software Engineer
> WebCT 




More information about the jdom-interest mailing list