我想用列表中保存的值替换子元素的text元素。
<weighting name="weighting">
<aWeight>false</aWeight>
<cWeight>true</cWeight>
</weighting>
我正在尝试将aWeight的文本值更改为true。我试图用这段代码来做。
elems = dom.findall('aWeight')
for elem in elems:
if user_settings.new_settings[5] == 'true':
'<aWeight>'.text = 'true'
dom.write('output.xml')
它正在编写文件,但值仍然保持为假。有没有人有任何建议。
答案 0 :(得分:0)
由于您的代码没有访问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)