Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python XML remove() Realign Element with ElementTree

I would like to remove the entire "value" element, but, when I do, it replaces it with the closing element </type> and messes up the formatting. Is there some way to simply delete the row and shift everything up?

XML Code:

    <type>
       <child name="someName" />
       <value name="Tier4" />
    </type>

Python:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for value in type.findall('./value'):
   if value.get('name') == 'Tier4':
   type.remove(value)

XML becomes:

    <type>
       <child name="someName" />
       </type>

>Solution :

Use xml.etree.ElementTree.indent(tree, space=' ', level=0) to prettify:

import xml.etree.ElementTree as ET

xml_s = """<type>
       <child name="someName" />
       <value name="Tier4" />
    </type>"""

elem = ET.fromstring(xml_s)

for value in elem.findall('./value'):
    if value.get('name') == 'Tier4':
        elem.remove(value)
        
ET.indent(elem, space='  ')
ET.dump(elem)

Output:

<type>
  <child name="someName" />
</type>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading