我在下面有一个XMl文件。我希望能够删除所有未称为john的孩子计划,并输出到新文件。
<data>
<plan_main>
<plan>
<name>John</name>
<id>1</id>
</plan>
<plan>
<name>Charlie</name>
<id>2</id>
</plan>
</plan_main>
<location>
<country>
<code>GB</code>
</country>
<country>
<code>DE</code>
</country>
</location>
</data>
我试过下面的代码,但列表中出现ValueError错误
for plan in root.findall('./plan_main/plan'):
name = plan.find('name').text
if name =! "john":
root.remove(plan)
tree.write('output.xml')
我希望我的输出文件如下所示:
<data>
<plan_main>
<plan>
<name>John</name>
<id>1</id>
</plan>
</plan_main>
<location>
<country>
<code>GB</code>
</country>
<country>
<code>DE</code>
</country>
</location>
</data>
但是我收到以下错误:
ValueError: list.remove(x): x not in list
假设=!
仅仅是复制/粘贴错误。问题在于,您正在尝试root
使用Element.remove()
method从节点中.remove()
删除元素,但仅当元素是的直接子元素时才删除它们root
。
如果要使用ElementTree
自身,可以更改XPath以遍历所有plan_main
元素,然后为每个plan_main
元素遍历其所有子元素,如果没有任何子元素名称john
,则将其删除。例子-
for plan_main in root.findall('./plan_main'):
for plan in plan_main:
name = plan.find('name').text
if name.lower() != "john":
plan_main.remove(plan)
演示-
>>> import xml.etree.ElementTree as ET
>>> s = """ <data>
... <plan_main>
... <plan>
... <name>John</name>
... <id>1</id>
... </plan>
... <plan>
... <name>Charlie</name>
... <id>2</id>
... </plan>
... </plan_main>
... <location>
... <country>
... <code>GB</code>
... </country>
... <country>
... <code>DE</code>
... </country>
... </location>
... </data>"""
>>> root = ET.fromstring(s)
>>> for plan_main in root.findall('./plan_main'):
... for plan in plan_main:
... name = plan.find('name').text
... if name.lower() != "john":
... plan_main.remove(plan)
...
>>> print(ET.tostring(root).decode('utf-8'))
<data>
<plan_main>
<plan>
<name>John</name>
<id>1</id>
</plan>
</plan_main>
<location>
<country>
<code>GB</code>
</country>
<country>
<code>DE</code>
</country>
</location>
</data>
如果可以使用lxml.etree
,则可以通过使用.getparent()
方法获取要删除的孩子的直接父母,从而对代码进行少量更改以使其正常工作。例子 -
for plan in root.findall('./plan_main/plan'):
name = plan.find('name').text
if name.lower() != "john":
plan.getparent().remove(plan)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句