How to delete node in xml using ElementTree in Python?

I read an example remove here and an example here does not apply to me.

My xml file reads:

 <A> <B>some text</B> <B>other text</B> <B>more text</B> </A> 

What I want to do is remove the second <B></B> from xml. I do not know what text it contains. But I have index <B></B> , for example index = 1, which means that I want to delete the second element (or node).

I have a code like this:

 F = open('example.xml') self.tree = parse(F) self.root = self.tree.getroot() F.close() 

So, in this case, I want to delete self.root[1] .

As it can be implemented with the help of ElementTree?

Edit: made my question more understandable and specific.

+4
source share
2 answers
 In [1]: import xml.etree.ElementTree as ET In [2]: xmlstr=\ ...: """ ...: <A> ...: <B>some text</B> ...: <B>other text</B> ...: <B>more text</B> ...: </A> ...: """ In [3]: tree=ET.fromstring(xmlstr) In [4]: tree.remove(tree.findall('.//B')[1]) / B> In [1]: import xml.etree.ElementTree as ET In [2]: xmlstr=\ ...: """ ...: <A> ...: <B>some text</B> ...: <B>other text</B> ...: <B>more text</B> ...: </A> ...: """ In [3]: tree=ET.fromstring(xmlstr) In [4]: tree.remove(tree.findall('.//B')[1]) 
+5
source

You guys are not straightforward. I combined my knowledge with the answers here and came out with this:

 for i, child in enumerate(self.root): if path == i: self.root.remove(child) break 

where path - index of the element that I want to delete.

+2
source

All Articles