簡體   English   中英

如何使用Python中的ElementTree刪除xml中的節點?

[英]How do I remove a node in xml using ElementTree in Python?

我讀過remove例子在這里和例子在這里並不適用於我。

我的xml文件是:

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

我想要做的是從xml中刪除第二個<B></B> 我不知道它有什么文字。 但我有<B></B>索引,比如index = 1,這意味着我想刪除第二個元素(或節點)。

我有這樣的代碼:

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

所以在這種情況下我要刪除的是self.root[1]

如何使用ElementTree實現?

編輯:讓我的問題更清晰,更具體。

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])

你們不是直截了當的。 我把我的知識與答案結合在一起,並得出了這個:

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

其中path是我要刪除的項的索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM