[jdom-interest] detach() from element

Bill Leng wleng at metatomix.com
Wed Mar 23 06:21:01 PST 2005


you should loop backward, something like
int n = my_lists.size();
for(int i = n-1; i >= 0; i--)
{
...
}

Bradley S. Huffman wrote:

>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
>_______________________________________________
>To control your jdom-interest membership:
>http://www.jdom.org/mailman/options/jdom-interest/youraddr@yourhost.com
>  
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.jdom.org/pipermail/jdom-interest/attachments/20050323/30bd14b8/attachment.htm


More information about the jdom-interest mailing list