Reputation: 59
I have an XML file that looks like this:
<StationConfig
StationId="1"
SportType="null"
StationType="null"
UseMetricSystem="US"
LocalTempStorageDrive="C:\"
LocalStorageDrive="C:\">
<ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable>
</StationConfig>
I'm trying to change the value of StationID through python and can't find a way. I've tried using Etree but cant figure out how to access the value in StationID and change it.
Sorry for the noob question, any help would be appreciated
Upvotes: 1
Views: 503
Reputation: 506
In your case the root is also the 'StationConfig' tag. Once you select it like this (or the find, findall functions), you can use the '.set' command to change its attributes.
from xml.etree.ElementTree import fromstring, ElementTree
xml_string = '<StationConfig StationId="1" SportType="null" StationType="null" UseMetricSystem="US" LocalTempStorageDrive="C:\" LocalStorageDrive="C:\"> <ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable> </StationConfig>'
tree = ElementTree(fromstring(xml_string))
root = tree.getroot()
root.set('StationId', 'the-new-value-you-want')
Upvotes: 2
Reputation: 1158
You can use the .set('attrname', 'value')
method.
import xml.etree.ElementTree as ET
xml_tree = ET.parse("xml_doc.xml")
root = xml_tree.getroot()
root.set("StationId", "123")
xml_tree.write("xml_doc_updated.xml")
Upvotes: 2