使用 lxml.objectify 替换节点文本,同时保留属性

发布于 2024-08-19 02:02:26 字数 473 浏览 3 评论 0原文

像这样使用 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 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

×眷恋的温暖 2024-08-26 02:02:26
>>> type(o.b)
<type 'lxml.objectify.StringElement'>

您正在用纯字符串替换元素。您需要将其替换为新的字符串元素。

>>> o.b = objectify.E.b('newtext', atr='someatr')

由于某种原因,你不能这样做:

>>> o.b.text = 'newtext'

但是,这似乎有效:

>>> o.b._setText('newtext')
>>> 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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文