这里是Python noob。想知道删除所有带有updated属性值true的"profile“标记的最干净和最好的方法是什么。
我尝试了以下代码,但它正在抛出:SyntaxError(“无法在元素上使用绝对路径”)
root.remove(root.findall("//Profile[@updated='true']"))XML:
<parent>
<child type="First">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Second">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Third">
<profile>
<other> </other>
</profile>
</child>
</parent>发布于 2016-09-05 20:39:16
如果使用xml.etree.ElementTree,则应使用remove()方法删除节点,但这需要具有父节点引用。因此,解决办法:
import xml.etree.ElementTree as ET
data = """
<parent>
<child type="First">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Second">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Third">
<profile>
<other> </other>
</profile>
</child>
</parent>"""
root = ET.fromstring(data)
for child in root.findall("child"):
for profile in child.findall(".//profile[@updated='true']"):
child.remove(profile)
print(ET.tostring(root))指纹:
<parent>
<child type="First">
</child>
<child type="Second">
</child>
<child type="Third">
<profile>
<other> </other>
</profile>
</child>
</parent>注意,对于lxml.etree,这可能会更简单一些:
root = ET.fromstring(data)
for profile in root.xpath(".//child/profile[@updated='true']"):
profile.getparent().remove(profile)其中ET是:
import lxml.etree as EThttps://stackoverflow.com/questions/39337042
复制相似问题