replacing node text using lxml.objectify while preserving attributes

主宰稳场 提交于 2019-12-22 08:15:43

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/2150838/replacing-node-text-using-lxml-objectify-while-preserving-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!