Christopher
Christopher

Reputation: 21

How to update the text of a tag in XML using Elementree

Using elementree, the easiest way to read the text of a tag is to do the following:

import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMaps/KeyMap_Checklist.xml")
host = sKeyMap.findtext("/BrowserInformation/BrowserSetup/host")

Now I want to update the text in the same file, hopefully without having to re-write it with something easy like:

host = "4444"
sKeyMap.replacetext("/BrowserInformation/BrowserSetup/host")

Any ideas?

Thx in advance Christopher

Upvotes: 2

Views: 226

Answers (2)

Luke Stanley
Luke Stanley

Reputation: 1294

building on Tendayi's example maybe try something like:

newXmlContent = ET.tostring(sKeyMap)
fileObject = open("KeyMaps/newKeyMap_Checklist.xml","w") #note I used a different filename for testing!
fileObject.write(newXmlContent)
fileObject.close()

Upvotes: 1

Tendayi Mawushe
Tendayi Mawushe

Reputation: 26138

If you want to update the value of the <host> element in your text file you should get a handle to the element using find() rather than just reading the text using findtext(). Once you have the element you can easily get the text out using element.text. Since you have the element you can easily reset its value as shown below:

import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMaps/KeyMap_Checklist.xml")
host_element = sKeyMap.find("/BrowserInformation/BrowserSetup/host")
host = host_element.text
print host
# Now reset the the text of the <host> element
host = "4444"
host_element.text = host

Upvotes: 1

Related Questions