2

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.

nrs
  • 937
  • 3
  • 17
  • 42
  • Please share a relevant sample of the code you have tried. – Simon May 25 '19 at 14:33
  • Possible duplicate of [Find and Replace Values in XML using Python](https://stackoverflow.com/questions/6523886/find-and-replace-values-in-xml-using-python) – Kamal Nayan May 25 '19 at 15:07

2 Answers2

1

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>
Kamal Nayan
  • 1,890
  • 21
  • 34
  • It's modifying the value but attribute places are sorting in alphabetical order. Ex: showing as . It should not change the attribute places. How can we do that? – nrs May 26 '19 at 02:12
  • Attribute places doesn't matter in xml – Kamal Nayan May 26 '19 at 03:51
  • But our project requirement is like attribute should be in same order after modifying. How can we do that? – nrs May 26 '19 at 04:10
  • @rts: Edited the answer to use module `lxml`, just one line change. Please note this is not internal module, you have to install it – Kamal Nayan May 26 '19 at 11:59
0

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')
F Blanchet
  • 1,430
  • 3
  • 21
  • 32