tags:

views:

61

answers:

2

Using ElementTree, I want to do the following:

1 - Open an XML file and read the text of a tag (works).

2 - Print out that value then change the value (works).

3 - Write the changed value back to the same tag in the XML file (Doesn't work).

import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMap_Checklist.xml")
port_element = sKeyMap.find("/BrowserInformation/BrowserSetup/port")
port = port_element.text
print port
port = "2222"
port_element.text = port
newXmlContent = ET.tostring(sKeyMap)
fileObject = open("KeyMap_Checklist.xml", "w")
fileObject.write(newXmlContent)
fileObject.close()

Thx in advance

A: 

Thx for the assist. Steps 1 - 7 work fine; they get the value from the XML file, print out the value, "4444", then change the value to "2222". When step 8 is executed, "newXmlContent = ET.tostring(sKeyMap)", the error "exceptions. AssertionError" is displayed.

Here's what the XML file "KeyMap_Checklist.xml" looks like:

<?xml version="1.0"?>
<testcasedata>
    <BrowserInformation>
        <BrowserSetup>
            <host>localhost</host>
            <port>4444</port>
        <BrowserSetup>
    <BrowserInformation>
</testcasedata>

What I'm trying to do with steps 7 - 11 is save the changed text back to the exact same tag that I initially read it from. So, after step 11 is done, the XML file should look like:

<?xml version="1.0"?>
<testcasedata>
    <BrowserInformation>
        <BrowserSetup>
            <host>localhost</host>
            <port>2222</port>
        <BrowserSetup>
    <BrowserInformation>
</testcasedata>

So 'port' was initially "4444" before the script started and after the script is done, the value is now "2222". I hope this is clearer but if not, plz let me know and thx again for your help.

Christopher
A: 

Any one have an idea on how to write back the changed value to the XML file without re-creating the file?

Christopher