简体   繁体   中英

ElementTree Remove Element

Python noob here. Wondering what's the cleanest and best way to remove all the " profile " tags with updated attribute value of true .

I have tried the following code but it's throwing: 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>

If you are using xml.etree.ElementTree , you should use remove() method to remove a node, but this requires you to have the parent node reference. Hence, the solution:

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))

Prints:

<parent>
  <child type="First">
    </child>
  <child type="Second">
    </child>
  <child type="Third">
     <profile>
       <other> </other>
    </profile>
  </child>
</parent>

Note that with lxml.etree this would be a bit simpler:

root = ET.fromstring(data)
for profile in root.xpath(".//child/profile[@updated='true']"):
    profile.getparent().remove(profile)

where ET is:

import lxml.etree as ET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM