1

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

2 Answers 2

2

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")
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, How can I save this to a new file?
Thanks for you answer mate. The thing is the file is already spaced out and has comments and I would rather to keep it in this format. If I'm not saving it to a new file the values won't change. If I'm saving it to a new file the new file is unformatted with the changed value
Please mark it as the accepted answer if it helped you.
Any idea why the value wont change in the original file but they do change if i save to another file?
@AvivKaplan: you are moving the goalposts by adding more requirements that are not in the original question. Please ask about one issue at a time. If you have problems with formatting for example, please ask a separate question (but first you should search for similar questions).
|
2

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.