如何使用Python中的ElementTree删除xml中的节点? [英] How do I remove a node in xml using ElementTree in Python?
问题描述
我的xml文件显示为:
< A>
< B>一些文本< / B>
< B>其他文字< / B>
< B>更多文字< / B>
< / A>
我要做的是删除第二个< B>< ; / B>
来自xml。我不知道它包含什么文字。但是我有< B< / B>
的索引,说index = 1,这意味着我要删除第二个元素(或节点)。 / p>
我有这样的代码:
F = open(' example.xml')
self.tree = parse(F)
self.root = self.tree.getroot()
F.close()
因此在这种情况下,我要删除的是 self.root [1]
。
如何使用ElementTree来实现?
编辑:让我的问题更加明确和具体。> p>
在[1]中:将xml.etree.ElementTree导入为ET
$ b [b]在[2]中:xmlstr = \
...:
...:< A>
...:< B>某些文本< / B>
...:< B>其他文本< / B>
...:< B>更多文本< / B>
...:< / A>
...:
在[3]中:tree = ET.fromstring(xmlstr)
在[4]:tree.remove (tree.findall('.// B')[1])$ b $ b
I've read the remove
example here and the example here is not applicable 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 to remove the second <B></B>
from the xml. 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).
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]
.
How can this be implemented using 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])
这篇关于如何使用Python中的ElementTree删除xml中的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!