gpt4 book ai didi

python - 在 Python 中更改 XML 值

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:36 25 4
gpt4 key购买 nike

如果我有如下所示的 XML 文件,我如何才能将版本从 50 更改为 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>

我已经尝试了多种方法来做到这一点,有些方法什么也没做,或者它只是创建了一个新版本的 unturnedVersion,代码底部有 51。我只想将 50 更改为 51 或我设置的任何其他值。

谢谢!

最佳答案

使用xml.etree.ElementTree .通过例如 find() 定位元素,通过 .attrib dictionary 更新 version 属性元素的:

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

打印:

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

请注意,如果您想增加现有版本,请使用:

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

而且,如果您从文件中读取 XML,请使用 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))

关于python - 在 Python 中更改 XML 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39169961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com