shekhar
shekhar

Reputation: 13

Update a specific tag in xml using python 2.7

Hi i have a xml like this i want to update the value between tags.

<ABC>
    <CDF ExcludeDefaults="false" MaxServers="-1">
         <action type="update">
             <prime>f3f09ff2a2244343a0b6b30dbb79a56b</prime>
         </action>
    </CDF>
</ABC>

i have soome value in a variable called close.

close = 'gdai55ff2a2244343a0b6b30dbb745rtdf' . i want to update prime tag with the value assigned to close . after update i want my xml to be in below format

<ABC>
    <CDF ExcludeDefaults="false" MaxServers="-1">
         <action type="update">
             <prime>gdai55ff2a2244343a0b6b30dbb745rtdf</prime>
         </action>
    </CDF>
</ABC>

i want to do this using python code .

Upvotes: 1

Views: 46

Answers (2)

Ammar
Ammar

Reputation: 1314

this is a simple way to do it using regex to get the wanted text, and replace it with what you want:

import re
f = open('xmlfile', 'r')
data = f.read()
f.close()

close = 'gdai55ff2a2244343a0b6b30dbb745rtdf'

reg = re.compile(r'<prime>(.*?)</prime>')
list = re.split(reg, data)
list[1] = '<prime>'+ close + '</prime>'
result = ''.join(list)
print result

the output would look like this:

<ABC>
    <CDF ExcludeDefaults="false" MaxServers="-1">
         <action type="update">
             <prime>gdai55ff2a2244343a0b6b30dbb745rtdf</prime>
         </action>
    </CDF>
</ABC>

hope this helped.

Upvotes: 1

jfs
jfs

Reputation: 414905

>>> import xml.etree.ElementTree as etree
>>> root = etree.fromstring(xml)
>>> root.find('.//prime').text = "gdai55ff2a2244343a0b6b30dbb745rtdf"
>>> print etree.tostring(root)
<ABC>
    <CDF ExcludeDefaults="false" MaxServers="-1">
         <action type="update">
             <prime>gdai55ff2a2244343a0b6b30dbb745rtdf</prime>
         </action>
    </CDF>
</ABC>

Upvotes: 1

Related Questions