[英]Parse xml type file
我有一个xml类型的文档:
<configuration>
<appSettings>
<add key="title" value="Donny" />
<add key="updaterApplication" value="Updater v4.3" />
</appSettings>
</configuration>
当添加key="updaterApplication"
时,我需要修改特定的条目,例如将value="Updater v4.3"
更改为value="Updater v4.4"
key="updaterApplication"
。
我尝试过:
import xml.etree.ElementTree as ET
tree = ET.parse(my_file_name)
root = tree.getroot()
tkr_itms = root.findall('appSettings')
for elm in tkr_itms[0]:
print(elm)
print(elm.attributes)
print(elm.value)
print(elm.text)
但是无法解决'< ... />'
之间的内容。
我看到您发现“ << />”之间的内容是属性。
遍历add
元素并检查key
属性值的另一种方法是检查谓词中的属性值。
例...
蟒蛇
import xml.etree.ElementTree as ET
tree = ET.parse("my_file_name")
root = tree.getroot()
root.find('appSettings/add[@key="updaterApplication"]').attrib["value"] = "Updater v4.4"
print(ET.tostring(root).decode())
输出量
<configuration>
<appSettings>
<add key="title" value="Donny" />
<add key="updaterApplication" value="Updater v4.4" />
</appSettings>
</configuration>
没关系 ... :
import xml.etree.ElementTree as ET
tree = ET.parse(my_file_name)
root = tree.getroot()
for elm in root.iter('add'):
if elm.attrib['key']=='updaterApplication':
elm.attrib['value'] = 'Updater v4.4'
print(elm.attrib)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.