Message377726
We can remove elements using Element.remove(). Let’s say we want to remove all countries with a rank higher than 50:
>>>
>>> for country in root.findall('country'):
... rank = int(country.find('rank').text)
... if rank > 50:
... root.remove(country)
...
>>> tree.write('output.xml')
When the original xml has over 2 country with rank>50,and they are one by one neighborly siblings element,the upper code will delete the 1st 3rd 5th and more odd No. country.
A proper example should be:
index=0
while index < len(root.findall("./*")):
rank = int (root[index].find("rank").text)
if rank>50:
root.remove(root[index])
index=index+0
continue
index=index+1
I think "for each in list" should not work by index,but should work by pointer like thing,could be a list of pointers.
A finial solution should be like this --- when the "for each in list" was acting,the pointers list would be fixed,and you need not to worry about the "list" changing. |
|
Date |
User |
Action |
Args |
2020-10-01 00:08:35 | WoodyWoo | set | recipients:
+ WoodyWoo, docs@python |
2020-10-01 00:08:35 | WoodyWoo | set | messageid: <1601510915.6.0.455772572055.issue41899@roundup.psfhosted.org> |
2020-10-01 00:08:35 | WoodyWoo | link | issue41899 messages |
2020-10-01 00:08:35 | WoodyWoo | create | |
|