如何在 python 3 中编辑 xml 配置文件?

How to edit xml config file in python 3?

我有一个 xml 配置文件,需要更新特定的属性值。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <testCommnication>
          <connection intervalInSeconds="50" versionUpdates="15"/>
        </testCommnication>
</configuration>

我只需要将 "versionUpdates" 值更新为“10”。

我怎样才能在 python 3.

中实现这个

我已经尝试了 xml.etree 和 minidom 但无法实现。

你可以在Python 3中使用xml.etree.ElementTree来处理XML :

import xml.etree.ElementTree
config_file = xml.etree.ElementTree.parse('your_file.xml')
config_file.findall(".//connection")[0].set('versionUpdates', 10))
config_file.write('your_new_file.xml')

请使用xml.etree.ElementTree修改xml:
编辑:如果要零售属性顺序,请改用lxml。要安装,请使用 pip install lxml

# import xml.etree.ElementTree as ET
from lxml import etree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()

# modifying an attribute
for elem in root.iter('connection'):
    elem.set('versionUpdates', '10')

tree.write('modified.xml')   # you can write 'sample.xml' as well

现在modified.xml中的内容:

<configuration>
    <testCommnication>
          <connection intervalInSeconds="50" versionUpdates="10" />
        </testCommnication>
</configuration>