ElementTree Remove Element
<p>Python noob here. Wondering what's the cleanest and best way to <strong>remove</strong> all the "<code>profile</code>" tags with <code>updated</code> attribute value of <code>true</code>. </p>

<p>I have tried the following code but it's throwing: <strong>SyntaxError("cannot use absolute path on element")</strong></p>

<pre><code> root.remove(root.findall("//Profile[@updated='true']"))
</code></pre>

<p>XML:</p>

<pre><code>&lt;parent&gt;
  &lt;child type="First"&gt;
    &lt;profile updated="true"&gt;
       &lt;other&gt; &lt;/other&gt;
    &lt;/profile&gt;
  &lt;/child&gt;
  &lt;child type="Second"&gt;
    &lt;profile updated="true"&gt;
       &lt;other&gt; &lt;/other&gt;
    &lt;/profile&gt;
  &lt;/child&gt;
  &lt;child type="Third"&gt;
     &lt;profile&gt;
       &lt;other&gt; &lt;/other&gt;
    &lt;/profile&gt;
  &lt;/child&gt;
&lt;/parent&gt;
</code></pre>

<p>If you are using <code>xml.etree.ElementTree</code>, you should use <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove" rel="nofollow"><code>remove()</code></a> method to remove a node, but this requires you to have the parent node reference. Hence, the solution:</p>

<pre><code>import xml.etree.ElementTree as ET

data = """
&lt;parent&gt;
  &lt;child type="First"&gt;
    &lt;profile updated="true"&gt;
       &lt;other&gt; &lt;/other&gt;
    &lt;/profile&gt;
  &lt;/child&gt;
  &lt;child type="Second"&gt;
    &lt;profile updated="true"&gt;
       &lt;other&gt; &lt;/other&gt;
    &lt;/profile&gt;
  &lt;/child&gt;
  &lt;child type="Third"&gt;
     &lt;profile&gt;
       &lt;other&gt; &lt;/other&gt;
    &lt;/profile&gt;
  &lt;/child&gt;
&lt;/parent&gt;"""

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))
</code></pre>

<p>Prints:</p>

<pre><code>&lt;parent&gt;
  &lt;child type="First"&gt;
    &lt;/child&gt;
  &lt;child type="Second"&gt;
    &lt;/child&gt;
  &lt;child type="Third"&gt;
     &lt;profile&gt;
       &lt;other&gt; &lt;/other&gt;
    &lt;/profile&gt;
  &lt;/child&gt;
&lt;/parent&gt;
</code></pre>

<hr>

<p>Note that with <code>lxml.etree</code> this would be a bit simpler:</p>

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

<p>where <code>ET</code> is:</p>

<pre><code>import lxml.etree as ET
</code></pre>

python xml python-2.7 scripting elementtree