【问题标题】:ElementTree Remove ElementElementTree 删除元素
【发布时间】:2017-01-13 04:55:22
【问题描述】:

这里是 Python 菜鸟。想知道删除所有带有updated 属性值为true 的“profile”标签的最干净和最好的方法是什么。

我尝试了以下代码,但它正在抛出:SyntaxError("cannot use absolute path on element")

 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>

【问题讨论】:

    标签: python xml python-2.7 scripting elementtree


    【解决方案1】:

    如果你使用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 ET
    

    【讨论】:

    • 感谢您的解决方案。我格式化了我的实际 XML 实现,并且您的代码没有删除其上的 Profile 标签。 (不是你的错)。我会接受你的回答并重新发布一个新问题。
    • @user1195192 不用担心 - 只需更新 XML,我会适当地更新代码。
    • 谢谢。我想到了。需要另一个 for 循环。 lxml 代码看起来干净多了。
    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2016-09-17
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多