How to add/remove only specific blocks of XML to a new file?

I’m trying to filter an XML such that only specific blocks of XML would be needed I have the original XML like this

<PROJECT>
  <BLOCKLIST>
      <BLOCK>
        <TASK>
            <INSTALL_METHOD installer="TYPE 1" />
            <FILE>
                <INSTALL_OPTIONS option="signature"/>
                <INSTALL_OPTIONS option="checksum"/>
            </FILE>
        </TASK>
        <TASK>
             <INSTALL_METHOD installer="TYPE 2" />
             <FILE>
                <INSTALL_OPTIONS option="signature"/>
                <INSTALL_OPTIONS option="checksum"/>
             </FILE>
         </TASK>
         <TASK>
            <INSTALL_METHOD installer="TYPE 3" />
            <FILE>
                <INSTALL_OPTIONS option="signature"/>
                <INSTALL_OPTIONS option="checksum"/>
            </FILE>
        </TASK>
        <TASK>
            <INSTALL_METHOD installer="TYPE 4" />
            <FILE>
                <INSTALL_OPTIONS option="signature"/>
                <INSTALL_OPTIONS option="checksum"/>
            </FILE>
        </TASK>
    </BLOCK>
  </BLOCKLIST>
</PROJECT>

Now I need to compare <INSTALL_METHOD installer="x" /> and move the entire TASK block to a new file , so for example, if I want only TYPE 1 and TYPE 3 the new.xml should look something like this

<PROJECT>
<BLOCKLIST>
    <BLOCK>
      <TASK>
        <INSTALL_METHOD installer="TYPE 1" />
        <FILE>
            <INSTALL_OPTIONS option="signature"/>
            <INSTALL_OPTIONS option="checksum"/>
        </FILE>
      </TASK>
      <TASK>
        <INSTALL_METHOD installer="TYPE 3" />
        <FILE>
            <INSTALL_OPTIONS option="signature"/>
            <INSTALL_OPTIONS option="checksum"/>
        </FILE>
      </TASK>
    </BLOCK>
</BLOCKLIST>
</PROJECT>

I tried the below approach, but I’m getting the following error ValueError: list.remove(x): x not in list.

import xml.etree.ElementTree as ET

tree = ET.parse("input.xml")
root = tree.getroot()
tasks = root.findall(".//BLOCKLIST/BLOCK/TASK")
   
for task in tasks:
    install_method = task.find("INSTALL_METHOD")
    if not install_method.get("installer") in ["TYPE 1" , "TYPE 3"]:
        root.remove(task)

tree.write("new.xml", encoding='UTF-8', xml_declaration=True)

>Solution :

The task is not a direct child of root, so you can’t remove it like this. If you use lxml.etree instead of xml.etree.ElementTree you can get the task parent and use it to remove the task (the rest of the code is without change)

import lxml.etree as ET

...
if not install_method.get("installer") in ["TYPE 1", "TYPE 3"]:
    task.getparent().remove(task)
...

Leave a Reply