使用 lxml.objectify 替换节点文本,同时保留属性
像这样使用 lxml.objectify
:
from lxml import objectify
o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>")
o.b = 'newtext'
导致 newtext
,丢失节点属性。它似乎是直接用新创建的元素替换该元素,而不是简单地替换元素的文本。
如果我尝试使用 obtext = 'newtext',它会告诉我 “StringElement”对象的属性“text”不可写
。
有没有一种方法可以在 objectify 中执行此操作,而不必将其拆分为不同的元素并涉及 etree?我只是想替换内部文本,同时保留节点的其余部分。我觉得我在这里缺少一些简单的东西。
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 thatattribute '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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在用纯字符串替换元素。您需要将其替换为新的字符串元素。
由于某种原因,你不能这样做:
但是,这似乎有效:
You are replacing an element with a plain string. You need to replace it with a new string element.
For some reason you can't just do:
However, this seems to work: