Replacing node text using lxml.objectify while saving attributes

Using lxml.objectify as follows:

 from lxml import objectify o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>") ob = 'newtext' 

results in <a><b>newtext</b></a> , losing the node attribute. It seems to directly replace the element with a new one, and not just replace the element text.

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

Is there a way to do this as part of objectification without having to split it into another element and include etree? I just want to replace the inner text, leaving only the rest of the node. I feel like I'm missing something simple here.

+4
source share
1 answer
 >>> type(ob) <type 'lxml.objectify.StringElement'> 

You replace the element with a simple string. You need to replace it with a new string element.

 >>> ob = objectify.Eb('newtext', atr='someatr') 

For some reason you cannot just do:

 >>> obtext = 'newtext' 

However, this seems to work:

 >>> ob_setText('newtext') 
+9
source

Source: https://habr.com/ru/post/1299597/


All Articles