【发布时间】:2021-11-11 11:12:29
【问题描述】:
我正在尝试根据子元素“id”值从根中删除多个“交易”子元素。 我有 id 列表,并希望有一个循环来删除整个孩子的“交易”。
XML 代码如下。
<holdings>
<Traded>
<positionName>position1</positionName>
<id type="ISIN" exchange="BB">BE154</id>
<amount>400</amount>
<price currency="EUR">44.000000000000</price>
</Traded>
<Traded>
<positionName>position2</positionName>
<id type="ISIN" exchange="FP">FR200</id>
<amount>200</amount>
<price currency="EUR">58.240000000000</price>
</Traded>
<Traded>
<positionName>position3</positionName>
<id type="ISIN" exchange="UN">US400</id>
<amount>100</amount>
<price currency="USD">413.310000000000</price>
</Traded>
<Traded>
<positionName>position4</positionName>
<id type="ISIN" exchange="UN">US15</id>
<amount>50000</amount>
<price currency="USD">20.120000000000</price>
</Traded>
</holdings>
不起作用的 Python 代码:
import xml.etree.ElementTree as ET
tree = ET.parse("positions.xml")
root = tree.getroot()
removelist = ["BE154", "FR200", "US400", "US15"]
for child in root:
for subelement in root.iter("id"):
for subelement.text in removelist:
child.remove
我们将不胜感激。
【问题讨论】:
-
一方面,你没有打电话给
.remove...