开发者

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 a开发者_运维问答ttribute. 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.


>>> 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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜