[jdom-interest] Patch: Element.getChildren(Namespace)

Hugh Emberson hugh at fifthweb.net
Tue Feb 20 18:41:43 PST 2001

Jason Hunter <jhunter at collab.net> writes:

> Hugh Emberson wrote:
> > 
> > Hi Guys,
> > 
> > The following patch adds the method getChildren(Namespace) to element.  This
> > came about because I found myself writing quite a few loops like this:
> >          Iterator itr = currentElement.getChildren().iterator();
> >          while (itr.hasNext()) {
> >            Element elem = (Element)itr.next();
> >           if(elem.getNamespaceURI() != NS)
> >              continue;
> >         }
> > I think it is also quite symmetrical with the other getChildren() methods.
> Could you please give some specific use cases for this?


You have a type of document that looks like this ("http://x.org/" if your

        <x:a xmlns:x="http://x.org/">
            <x:b />
            <x:c />
            <x:b />

(e.g., 'a' contains a mixture of 'b' and 'c')

Someone else creates one of these documents, but they annotate it with some
other elements in there namespace and then send it to you:

        <x:a xmlns:x="http://x.org" xmlns:y="http://y.org">
            <x:b /> 
            <y:p />
            <x:c />
            <y:q />

in the code that processes elements of type a, you only want to process the
children in your namespace, you can't possibly handle the other elements so
you either write the loop quoted above, or you use getChildren(Namespace):

        Iterator itr = currentElement.getChildren(myNamespace).iterator();
        while (itr.hasNext()) {
          Element elem = (Element)itr.next();

I admit that getChildren(Namespace) will only save you two lines of typing,
but it seems to me that those two lines will be written many times.


P.S.  There is a bug in the quoted loop.  It should read:

         Iterator itr = currentElement.getChildren().iterator();
         while (itr.hasNext()) {
           Element elem = (Element)itr.next();

It was late when I wrote it ...

More information about the jdom-interest mailing list