保留属性时使用lxml.objectify替换节点文本 [英] replacing node text using lxml.objectify while preserving attributes

查看:107
本文介绍了保留属性时使用lxml.objectify替换节点文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样使用lxml.objectify:

from lxml import objectify

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

o.b = 'newtext'

导致<a><b>newtext</b></a>,丢失node属性.似乎是用新创建的元素直接替换了元素,而不是简单地替换了元素的文本.

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.

如果我尝试使用o.b.text = 'newtext',它告诉我 attribute 'text' of 'StringElement' objects is not writable.

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

是否有一种方法可以在对象化内完成而不必将其拆分为另一个元素并涉及etree?我只是想替换内部文本,而使其余的节点保持独立.我觉得这里缺少一些简单的东西.

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'

但是,这似乎可行:

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

这篇关于保留属性时使用lxml.objectify替换节点文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆