Reputation: 945
I have a xml config file and needs to update particular attribute value.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<testCommnication>
<connection intervalInSeconds="50" versionUpdates="15"/>
</testCommnication>
</configuration>
I just need to update the "versionUpdates" value to "10".
How can i achieve this in python 3.
I have tried xml.etree and minidom and not able to achieve it.
Upvotes: 2
Views: 966
Reputation: 1960
Please use xml.etree.ElementTree
to modify the xml:
Edit: If you want to retail the attribute order, use lxml
instead. To install, use pip install lxml
# import xml.etree.ElementTree as ET
from lxml import etree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
# modifying an attribute
for elem in root.iter('connection'):
elem.set('versionUpdates', '10')
tree.write('modified.xml') # you can write 'sample.xml' as well
Content now in modified.xml
:
<configuration>
<testCommnication>
<connection intervalInSeconds="50" versionUpdates="10" />
</testCommnication>
</configuration>
Upvotes: 1
Reputation: 1510
You can use xml.etree.ElementTree
in Python 3 to handle XML :
import xml.etree.ElementTree
config_file = xml.etree.ElementTree.parse('your_file.xml')
config_file.findall(".//connection")[0].set('versionUpdates', 10))
config_file.write('your_new_file.xml')
Upvotes: 0