简体   繁体   中英

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.

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. 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 ). 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):

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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