Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing node text using lxml.objectify while preserving attributes

Tags:

python

xml

lxml

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.

like image 331
Paul McMillan Avatar asked Jan 22 '23 16:01

Paul McMillan


1 Answers

>>> 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')
like image 104
Lennart Regebro Avatar answered Apr 06 '23 19:04

Lennart Regebro