Rename object in lxml

Let’s assume we have a xml file like this:

<annotation verified="yes">

Now I want to change the name of all objects in a given xml file.

I wrote the following function:

def _rename_objects(tree, path, new_name="new_name"):
    root = tree.getroot()
    for rank in root.iter('object'):
        rank.text = str(new_name)

What it does is, it places the text to object. How do I replace the value in ‘name’? Unfortunately tree elements are not really printable for debugging.

<Element 'object' at 0x11235d400>

New values after _rename_objects look like this:



You need to use [0] index to get node content instead of the node itself.

rank <Element object>
rank[0] <Element name>

for rank in root.iter("object"):
    rank[0].text = str(new_name)