Aubtin Samai
Aubtin Samai

Reputation: 1361

Change an XML Value in Python

If I have an XML file such as below, how would I be able to change the version from 50 to 51?

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <updateCheck seconds="2" />
    <unturnedVersion version="50" />
    <unturnedFolder recoveryBundlesAfterUpdates="false" />
    <rocket useRocket="true" apikey=""/>
    <steam username="" password="" />
    <steamUpdates validate="true" />
    <servers rconEnabled="false">
        <server name="server1" rconPort="27013" rconPassword="pass" />
        <server name="server2" rconPort="27014" rconPassword="pass" />
    </servers>
    <notifyBefore seconds="60" />
</config>

I've tried multiple methods to do it, and some don't do anything or it just creates a new version of the unturnedVersion with 51 at the bottom of the code. I want to simply change 50 to 51 or any other value I set.

Thanks!

Upvotes: 1

Views: 108

Answers (1)

alecxe
alecxe

Reputation: 473763

Use xml.etree.ElementTree. Locate the element via, for example, find(), update the version attribute through the .attrib dictionary of an element:

import xml.etree.ElementTree as ET

data = """<?xml version="1.0" encoding="UTF-8"?>
<config>
    <updateCheck seconds="2" />
    <unturnedVersion version="50" />
    <unturnedFolder recoveryBundlesAfterUpdates="false" />
    <rocket useRocket="true" apikey=""/>
    <steam username="" password="" />
    <steamUpdates validate="true" />
    <servers rconEnabled="false">
        <server name="server1" rconPort="27013" rconPassword="pass" />
        <server name="server2" rconPort="27014" rconPassword="pass" />
    </servers>
    <notifyBefore seconds="60" />
</config>"""

root = ET.fromstring(data)
unturned_version = root.find("unturnedVersion")
unturned_version.attrib["version"] = "51"

print(ET.tostring(root))

Prints:

<config>
    <updateCheck seconds="2" />
    <unturnedVersion version="51" />
    <unturnedFolder recoveryBundlesAfterUpdates="false" />
    <rocket apikey="" useRocket="true" />
    <steam password="" username="" />
    <steamUpdates validate="true" />
    <servers rconEnabled="false">
        <server name="server1" rconPassword="pass" rconPort="27013" />
        <server name="server2" rconPassword="pass" rconPort="27014" />
    </servers>
    <notifyBefore seconds="60" />
</config>

Note that, if you want to increment the existing version, use:

unturned_version.attrib["version"] = str(int(unturned_version.attrib["version"]) + 1)

And, if you read an XML from file, use ET.parse():

import xml.etree.ElementTree as ET


tree = ET.parse("input.xml")
root = tree.getroot()
unturned_version = root.find("unturnedVersion")
unturned_version.attrib["version"] = str(int(unturned_version.attrib["version"]) + 1)

print(ET.tostring(root))

Upvotes: 5

Related Questions