[jdom-interest] Iterator.remove() is calling a non-overloaded method to remove children from an element.
Travers Waker
traversw at innoforge.co.za
Wed Sep 27 03:56:01 PDT 2000
Hi.
Calling Element.getChildren() returns a "live" list that modifies the
original XML document tree. Whatever list JDOM returns obiviously has
overloaded methods for List.remove(Element name) to unset the pointer this
elements parent Element and perform other similar JDOM-specific tasks.
However, when one get's an Iterator for this List (i.e.
Element.getChildren().iterator()), the Iterator.remove() method calls a
method of the underlying list that is not overloaded to update the internal
fields of Element (e.g Element.parent). The following code illustrates the
problem: (The code just moves a child element from parent1 to parent2).
package tests.jdom;
import java.util.*;
import org.jdom.*;
class JdomListTest2 {
public static void main(String[] args) throws Exception {
Element parent1 = new Element("parent1");
Element parent2 = new Element("parent2");
parent1.addContent(new Element("child"));
List list = parent1.getChildren();
Iterator it = list.iterator();
Element child = (Element)it.next();
// list.remove(child);
it.remove();
parent2.addContent(child);
}
}
The error generated is:
org.jdom.IllegalAddException: The element "child" could not be added as a
child of "parent2": The element already has an existing parent "parent1"
at org.jdom.Element.addContent(Element.java:846)
at tests.jdom.JdomListTest2.main(JdomListTest2.java:20)
Exception in thread "main"
If I uncomment "list.remove(child)" and comment out "it.remove()",
everything works as expected. This is not as efficient as using
it.remove(), because list.remove(child) involves searching through the list
again for teh "child" element, even though the Iterator (it) is pointing to
exact location of child already!
Shouldn't be that hard to fix, but it would take a while to get familiar
with the JDOM code and CVS, so I think I'd better let someone who knows what
they're doing add support for Iterator.remove().
Thanks
Travers
More information about the jdom-interest
mailing list