Search code examples
pythonxmlelementchildren

Python : Remove an element but not its children from xml?


I want to remove element but not its children. I tried with this code, but my code remove its children also.

code

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

for item in root.findall('item'):
    root.remove(item)

print(ET.tostring(root))
>>> <root>
    </root>

test.xml

<?xml version="1.0" ?>
<root>
    <item>
        <data>
            <number>01</number>
            <step>one</step>
        </data>
    </item>
</root>

expected outcome

<?xml version="1.0" ?>
<root>
    <data>
        <number>01</number>
        <step>one</step>
    </data>
</root>

Solution

  • You should move all children of item to root before removing

    for item in root.findall('item'):
        for child in item:
            root.append(child)
        root.remove(item)
    
    print(ET.tostring(root))
    

    the code results in

    <root>
       <data>
           <number>01</number>
           <step>one</step>
       </data>
    </root>