pythonlxml

Insert attibute in position


I need to insert an element attribute at the correct position using the lxml library.

Here is an example where I am trying to insert the attr2 attribute in front of the attr3 attribute:

from lxml import etree

xml = '<root attr0="val0" attr1="val1" attr3="val3" attr4="val4" attr5="val5"/>'
root = etree.fromstring(xml)

inse_pos = root.keys().index('attr3')
attrib_items = root.items()
attrib_items.insert(inse_pos, ('attr2', 'val2'))
root.attrib = dict(attrib_items)

print(etree.tostring(root))

But I'm getting an error: AttributeError: attribute 'attrib' of 'lxml.etree._Element' objects is not writable


Solution

  • One possible solution could be to recreate the element attributes from scratch:

    from lxml import etree
    
    xml = '<root attr0="val0" attr1="val1" attr3="val3" attr4="val4" attr5="val5"/>'
    root = etree.fromstring(xml)
    
    attribs = root.attrib.items()
    root.attrib.clear()
    
    for k, v in attribs:
        if k == "attr3":
            root.attrib["attr2"] = "val2"
        root.attrib[k] = v
    
    print(etree.tostring(root))
    

    Prints:

    b'<root attr0="val0" attr1="val1" attr2="val2" attr3="val3" attr4="val4" attr5="val5"/>'