Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 433
user1195192 Avatar asked Nov 02 '25 18:11

user1195192


1 Answers

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
like image 194
alecxe Avatar answered Nov 05 '25 07:11

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!