[jdom-interest] detach() from element

Bradley S. Huffman hip at a.cs.okstate.edu
Tue Mar 22 16:29:26 PST 2005


kandryc at miser.umass.edu writes:

> I have an XML file structured something like the following:
> 
> <my-lists>
>    <list refid="1" date="3/22/2005 4:09 PM" />
>    <list refid="1" date="3/22/2005 4:14 PM" />
>    <list refid="1" date="3/22/2005 5:19 PM" /> 
>    <list refid="1" date="3/22/2005 6:01 PM" />
>    <list refid="2" date="3/22/2005 6:23 PM" /> 
> </my-lists>
> 
> However, when I execute the following code:
> 
> List my_lists = theDocument.getRootElement().getChildren();
> for (int i = 0; i < my_lists.size(); i++) {
>    Element next = (Element)my)lists.get(i);
>       if (next.getAttribute("refid").getValue().equals("1")) {
>          next.detach();
>       }
> }
> 
> The output XML is:
> 
> <my-lists>
>    <list refid="1" date="3/22/2005 4:14 PM" />
>    <list refid="1" date="3/22/2005 6:01 PM" />
>    <list refid="2" date="3/22/2005 6:23 PM" /> 
> </my-lists>
> 
> Why are not all the elements with refid="1" not detached?

Because when you remove a item from a list, all items following it
are shifted. For example if when i == 3 the if statement is true,
the 3rd element is removed and the old 4th element becomes the new
3rd, the old 5th becomes the new 4th, etc, etc. Then the loop ends
and i is incremented to 4, leaving what was the old 4th element untouched.

Brad


More information about the jdom-interest mailing list