如何使用带有 for 循环的 xpath (python) 更改 xml 中的节点值?

How to change the node values in xml using the xpath with for loop (python)?

我正在做一个 xml 项目,我尝试使用 python.

实现一些代码

我正在尝试使用 xpath 获取文本节点列表 (//text()) 并更改 for 循环中的值,但它没有在最终输出中更新。请帮助我修复代码以更改文本节点的值。

from lxml import etree
xml = "<main><a>y<b>x</b><c><d>x</d></c></a></main>"
root = etree.fromstring(xml)
nodeList = root.xpath('//text()')
for c in nodeList:
    c = "test"    
print (etree.tostring(root))

Output: 
<main><a>y<b>x</b><c><d>x</d></c></a></main>

nodeList 的每个元素都是一种特殊的字符串 (_ElementStringResult)。字符串是不可变的,因此无法分配新值。

这是有效的代码(它还考虑了 tail 属性):

from lxml import etree

xml = "<main><a>y<b>x</b>x<c><d>x</d>y</c></a></main>"
root = etree.fromstring(xml)

for node in root.iter():
    if node.text:
        node.text = "test"
    if node.tail:
        node.tail = "TAIL"

print(etree.tostring(root).decode())

输出:

<main><a>test<b>test</b>TAIL<c><d>test</d>TAIL</c></a></main>