解析xml类型文件

甲板

我有一个xml类型的文档:

<configuration>
    <appSettings>
        <add key="title" value="Donny" />
        <add key="updaterApplication" value="Updater v4.3" />
    </appSettings>
</configuration>

我需要在添加时修改特定条目,例如value="Updater v4.3"to 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>

有关ElementTree中XPath的更多信息,请参见此处。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章