如何在Python3中编辑xml配置文件?
我有一个xml配置文件,需要更新特定的属性值如何在Python3中编辑xml配置文件?,python,xml,config,Python,Xml,Config,我有一个xml配置文件,需要更新特定的属性值 <?xml version="1.0" encoding="utf-8"?> <configuration> <testCommnication> <connection intervalInSeconds="50" versionUpdates="15"/> </testCommnication> </configuration>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<testCommnication>
<connection intervalInSeconds="50" versionUpdates="15"/>
</testCommnication>
</configuration>
我只需要将“versionUpdate”值更新为“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安装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>
请分享您尝试过的代码的相关示例。可能重复的代码正在修改值,但属性位置按字母顺序排序。例如:显示为。它不应更改属性位置。我们如何做到这一点呢?属性位置在XML中并不重要,但我们的项目要求是属性在修改后应该保持相同的顺序。我们怎么能做到呢?@rts:编辑答案,使用modulelxml
,只需更改一行即可。请注意,这不是内部模块,您必须安装它