首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ElementTree删除元素

ElementTree删除元素
EN

Stack Overflow用户
提问于 2016-09-05 20:05:27
回答 1查看 9.3K关注 0票数 4

这里是Python noob。想知道删除所有带有updated属性值true的"profile“标记的最干净和最好的方法是什么。

我尝试了以下代码,但它正在抛出:SyntaxError(“无法在元素上使用绝对路径”)

代码语言:javascript
复制
 root.remove(root.findall("//Profile[@updated='true']"))

XML:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-05 20:39:16

如果使用xml.etree.ElementTree,则应使用remove()方法删除节点,但这需要具有父节点引用。因此,解决办法:

代码语言:javascript
复制
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))

指纹:

代码语言:javascript
复制
<parent>
  <child type="First">
    </child>
  <child type="Second">
    </child>
  <child type="Third">
     <profile>
       <other> </other>
    </profile>
  </child>
</parent>

注意,对于lxml.etree,这可能会更简单一些:

代码语言:javascript
复制
root = ET.fromstring(data)
for profile in root.xpath(".//child/profile[@updated='true']"):
    profile.getparent().remove(profile)

其中ET是:

代码语言:javascript
复制
import lxml.etree as ET
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39337042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档