解析 xml 类型文件

Parse xml type file

我有一个 xml 类型的文档:

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

我需要修改一个特定的条目,例如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)

但是无法访问'< ... />'.

之间的内容

没关系...:[=​​11=]

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)

我看你发现 "content between '< ... />' " 是属性。

迭代 add 元素并检查 key 属性值的替代方法是检查 predicate.

中的属性值

示例...

Python

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>

See here for more info on XPath in ElementTree.