用列表python中的值替换xml子元素文本

2024-09-29 23:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用列表中的值替换子元素的文本元素。在

<weighting name="weighting">
        <aWeight>false</aWeight>
        <cWeight>true</cWeight>
</weighting>

我正在尝试将aWeight的文本值更改为true。我试着用这个代码来做。在

^{pr2}$

它正在写入文件,但值仍保持为false。有人有什么建议吗。在


Tags: 文件代码name文本falsetrue元素列表
1条回答
网友
1楼 · 发布于 2024-09-29 23:15:17

由于您的代码没有访问elem变量来更改节点值,因此您需要告诉操作它需要在哪里操作。在

import xml.etree.ElementTree as ET
elems = ET.fromstring('<weighting><aWeight>false</aWeight><cWeight>true</cWeight></weighting>')

test_condition = ['false', 'not set', 'bananas']

elems2 = elems.findall("aWeight")
for elem in elems2:
    print elem.text
    if elem.text in test_condition: 
        elem.text = 'true' 
    print elem.text
print ET.tostring(elems)

相关问题 更多 >

    热门问题