Reputation: 21
I have the following XML file which is longer but I only pick out the part that I want to change. I like to change the text from 'false' to 'true' and write back to the same file name. I've searched and read a few threads and the closest I get is the code below, but it does not do as what I want.
Here is the file:
<settings>
<setting id="HomeMenuNoWeatherButton" type="bool">false</setting>
<setting id="HomeMenuNoPicturesButton" type="bool">false</setting>
<setting id="HomeMenuNoMusicButton" type="bool">false</setting>
</settings>
The code I've tried from one of the threads:
from xml.etree import ElementTree as et
tree = et.parse('path to settings.xml')
tree.find('settings/setting id="HomeMenuNoWeatherButton" type="bool"').text = 'true'
tree.find('settings/setting id="HomeMenuNoPicturesButton" type="bool"').text = 'true'
tree.find('settings/setting id="HomeMenuNoMusicButton" type="bool"').text = 'true'
tree.write('path to settings.xml')
I want the file to be:
<settings>
<setting id="HomeMenuNoWeatherButton" type="bool">true</setting>
<setting id="HomeMenuNoPicturesButton" type="bool">true</setting>
<setting id="HomeMenuNoMusicButton" type="bool">true</setting>
</settings>
Upvotes: 2
Views: 96
Reputation: 89285
Your selector expression isn't a valid XPath expression. Use []
for filter aka predicate and use @
for attribute, for example:
tree = et.parse('path to settings.xml')
root = tree.getroot()
xpath = 'setting[@id="HomeMenuNoWeatherButton" and @type="bool"]'
root.find(xpath).text = 'true'
Upvotes: 2
Reputation: 482
Instead of using:
tree.find('settings/setting id="HomeMenuNoWeatherButton" type="bool"').text = 'true'
Use:
tree.find('settings/setting id="HomeMenuNoWeatherButton" type="bool"').text.set('true')
Upvotes: -1