我有一个xml配置文件,需要更新特定的属性值。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<testCommnication>
<connection intervalInSeconds="50" versionUpdates="15"/>
</testCommnication>
</configuration>
我只需要将“ versionUpdates”值更新为“ 10”即可。
我如何在python 3中实现这一目标?
我尝试了xml.etree和minidom,但无法实现。
答案 0 :(得分:0)
您可以在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')
答案 1 :(得分:0)
请使用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>