[jdom-interest] Proper way to prune a tree with removeContent

Jeff Rosler Jeff.Rosler at flatironssolutions.com
Wed Nov 9 08:00:08 PST 2005

Hi All,


I'm running JDOM 1.0 and I just ran into an interesting corruption
problem. In my code, I'm parsing XML elements in a doc and removing
specific elements (branches) based on their attribute values. Please see
the code snippet below.


I initially call this code with profileDOM(null,doc.getRootElement()).
It recursively parses the tree until my checkAttributes() method returns
false. At this point, it removes that element. If it doesn't return
false then it gets the list of children and calls itself (recursion) for
each child.


The problem occurs in the removeContent call. The removeContent
correctly removes the content, but appears to screw up the list. The
second time that removeContent is called with a different parent, it
removes the wrong content node. It appears that the internal list
somehow gets screwed up. While I was debugging this in my IDE, I took a
look at the content list in the parent element and the
parent.indexOf(node) was returning the wrong index for the actual
content. In my sample, it returned a text node instead of an element!


So, two questions -

If this isn't the correct type of code to prune content, what is? I
remember trying an iterator a while back, but ended up getting some

The second is, isn't this a bug? Is this the right forum to report it?


    public void profileDOM(Element parent, Element node)  throws


        if (parent != null && !checkAttributes(node))


            // previously just doing parent.removeContent(node);

            int index = parent.indexOf(node);

            Content content = parent.removeContent(index);

            if (content == null)


                logger.info("Removal of element <" + node.getName() + ">





                List list = node.getChildren();

                for(int i=0;i<list.size();i++)


                    Element child = (Element)list.get(i);


                    // check to see if we should delete child







Jeff Rosler
Flatirons Solutions Corporation
XML and Content Management Solutions
2555 55th Street
Suite 100D
Boulder, CO  80301
303-544-0514 x111
jeff.rosler at flatironssolutions.com

"The man with a new idea is a crank until the idea succeeds"

Mark Twain


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.jdom.org/pipermail/jdom-interest/attachments/20051109/53707310/attachment.htm

More information about the jdom-interest mailing list