Search code examples
pythonxmllxml

replacing node text using lxml.objectify while preserving attributes


Using lxml.objectify like so:

from lxml import objectify

o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>")

o.b = 'newtext'

results in <a><b>newtext</b></a>, losing the node attribute. It seems to be directly replacing the element with a newly created one, rather than simply replacing the text of the element.

If I try to use o.b.text = 'newtext', it tells me that attribute 'text' of 'StringElement' objects is not writable.

Is there a way to do this within objectify without having to split it out into a different element and involving etree? I simply want to replace the inner text while leaving the rest of the node alone. I feel like I'm missing something simple here.


Solution

  • >>> type(o.b)
    <type 'lxml.objectify.StringElement'>
    

    You are replacing an element with a plain string. You need to replace it with a new string element.

    >>> o.b = objectify.E.b('newtext', atr='someatr')
    

    For some reason you can't just do:

    >>> o.b.text = 'newtext'
    

    However, this seems to work:

    >>> o.b._setText('newtext')