Skip to main content
 首页 » 编程设计

Python lxml 改变xml对象的子文本属性

2025年02月15日10xxx_UU

我有一个 xml,我从 API 输出中使用 objectify 对其进行了解析,我将其称为“结果”变量。现在我想保留对象,但只更改文本文件并将其返回给 API 以更新元素。

<field xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="multi_text_area"> 
  <id>1754</id> 
  <name>Devices under maintenance</name> 
  <read_only>false</read_only> 
  <text_area> 
    <text>defwhanld12x</text> 
  </text_area> 
</field> 

当我尝试更改我得到的文本时,出现错误:

result.text_area.text = 'This is a test' 

TypeError: attribute 'text' of 'ObjectifiedElement' objects is not writable

我还尝试剥离元素并重新创建它,因为 lxml 文档说您不能更改对象。

etree.strip_elements(result, 'text') 
etree.SubElement(result.text_area, 'text').text = 'This is just a test' 

但是得到类似的错误:

TypeError: attribute 'text' of 'StringElement' objects is not writable

请您参考如下方法:

这是因为您的元素名为 text . text也被 lxml.objectify 使用存储元素的内部文本,这就是冲突发生的方式。当你做 result.text_area.text , 它被解释为试图访问 text_area 的内部文本,而不是访问名为 text 的子元素.您可以通过访问 text 来避免此冲突。元素如下:

result.text_area['text'] = 'This is a test' 

更新:

上面原来是替换整个<text>带有新文本的元素,最终作为您在下面评论中提到的形式的元素:

<text xmlns:py="http://codespeak.net/lxml/objectify/pytype"  
      py:pytype="str">This is a test</text> 

更新text内部文本的正确方法元素将使用 _setText() ,如 this other answer 中所述:

result.text_area['text']._setText('This is a test')