简体   繁体   English

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

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

I'm doing a xml project where i try to implement some codes using python. 我正在做一个xml项目,我尝试使用python实现一些代码。

I am trying to get the list of text nodes (//text()) using the xpath and change the values in for loop, but it is not getting updated in final output. 我正在尝试使用xpath获取文本节点(// text())的列表并更改for循环中的值,但最终输出中未更新它。 Kindly help me to fix the code to change the values of the text nodes. 请帮助我修复代码以更改文本节点的值。

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>

Each element of nodeList is a special kind of string ( _ElementStringResult ). nodeList每个元素都是一种特殊的字符串( _ElementStringResult )。 Strings are immutable, so it is not possible to assign new values. 字符串是不可变的,因此无法分配新值。

Here is code that works (it also takes the tail property into account): 这是起作用的代码(它也考虑了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())

Output: 输出:

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

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

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