pythonxml

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:

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>