简体   繁体   English

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

[英]replacing node text using lxml.objectify while preserving attributes

Using lxml.objectify like so: 像这样使用lxml.objectify

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. 导致<a><b>newtext</b></a> ,丢失节点属性。 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 obtext = 'newtext' , it tells me that attribute 'text' of 'StringElement' objects is not writable . 如果我尝试使用obtext = 'newtext' ,它会告诉我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? 有没有办法在客观化中做到这一点,而不必将其分解为不同的元素并涉及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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM