[英]How do I remove a node in xml using ElementTree in Python?
I've read the remove
example here and the example here is not applicable to me. 我读过
remove
例子在这里和例子在这里并不适用于我。
My xml file reads: 我的xml文件是:
<A>
<B>some text</B>
<B>other text</B>
<B>more text</B>
</A>
What I want to do is to remove the second <B></B>
from the xml. 我想要做的是从xml中删除第二个
<B></B>
。 I do not know what text it holds. 我不知道它有什么文字。 But I have the index of the
<B></B>
, say index = 1, which means I want to remove the second element (or node). 但我有
<B></B>
索引,比如index = 1,这意味着我想删除第二个元素(或节点)。
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 what I want to remove is self.root[1]
. 所以在这种情况下我要删除的是
self.root[1]
。
How can this be implemented using ElementTree? 如何使用ElementTree实现?
Edit: Made my question more clear and specific. 编辑:让我的问题更清晰,更具体。
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])
You guys are not straight to the point. 你们不是直截了当的。 I've 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
is the index of the item I want to remove. 其中
path
是我要删除的项的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.