Q
Q
Qk4l2012-10-12 20:09:04
Python
Qk4l, 2012-10-12 20:09:04

element.remove(subelement) firing once in a loop

Kind people, please tell me where I made a mistake ...
There is an xml of the form

<server>
  <User> 
    <Username>user</Username>
    <Password>pass</Password>
      <list>
      <Item c="ru" askstatus="-1" recvstatus="-1" substatus="3" name="Roman"> </Item>
      <Item c="ru" askstatus="-1" recvstatus="-1" substatus="3" name="Roman"> </Item>
      <Item c="ru" askstatus="-1" recvstatus="-1" substatus="3" name="Roman"> </Item>
      <Item c="com askstatus="-1" recvstatus="-1" substatus="3" name="Roman"> </Item>
   </list>
  </User>
</server>


It is necessary to remove all item lines with the c="ru" attribute.

My code.

#!/usr/bin/env python
import xml.etree.ElementTree as etree
import sys
tree = etree.parse(sys.argv[1])
root = tree.getroot()

for user in root:                                                                                                                                                                                                   
    for param in user:
        if param.tag == 'list':
            for item in param:
                if str(item.get('c')) == 'ru': 
                    param.remove(item)
tree.write('output.xml')


The problem is that not all occurrences are removed, but only half.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Tyslyatsky, 2012-10-12
@Qk4l

If you look at ElementTree.__getitem_(self, index), you can see that with each iteration of item, index is passed to params: the first iteration is 0, the second is 1, and dt

    def __getitem__(self, index ):
        return self._children[index]

But, you remove elements from param, therefore:
at the first iteration, you have the first item, which will be deleted;
at the second item (which was the third), which is removed, we
exit the loop.
Total, you have two items in params

Q
Qk4l, 2012-10-12
@Qk4l

Found a solution:
Drive items into the list for deletion. And then, leaving the main loop, delete them.
I just still don't understand why. =(

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question