tastyminerals
tastyminerals

Reputation: 6548

Why I can't remove a subelement from xml.etree.ElementTree.Element?

I don't understand what is going on? I have xml.etree.ElementTree.Element objects with the following representation:

<root>
   <tag1>some text</tag1>
   <l1>text</l1>
   <l2>text</l2>
</root>

I want to remove <tag1>...</tag1> subelement. etree_collection is an OrderedDict that contains ElementTree.Element objects.

   for etree in etree_collection.values():
        tag1 = etree.iter('tag1')
        etree.remove(tag1)

This code produces ValueError: list.remove(x): x not in list error.

What is wrong here?

Upvotes: 0

Views: 1356

Answers (1)

unutbu
unutbu

Reputation: 880767

etree.iter('tag1') returns a ElementDepthFirstIterator:

In [175]: etree.iter('tag1')
Out[175]: <lxml.etree.ElementDepthFirstIterator at 0x7f43736a61e0>

You'd have to iterate through the items in the iterator to obtain <tag1> Elements:

In [176]: list(etree.iter('tag1'))
Out[176]: [<Element tag1 at 0x7f4373698ef0>]

Instead, you could use find to obtain the first <tag1> Element in etree:

In [177]: etree.find('tag1')
Out[177]: <Element tag1 at 0x7f4373698ef0>

So using find you might use something like:

for elt in etree_collection.values():
     tag1 = elt.find('tag1')
     elt.remove(tag1)

(I changed etree to elt since etree reminds me too much of the module xml.etree.)


If there can be more than one <tag1> Element in elt, then you could use

for elt in etree_collection.values():
    for tag1 in elt.iter('tag1'):
        elt.remove(tag1)

Upvotes: 2

Related Questions