解析xml类型文件

时间:2018-11-21 20:32:35

标签: python xml tags elementtree

我有一个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)

但是无法解决'< ... />'之间的内容。

2 个答案:

答案 0 :(得分:1)

我看到您发现“ << />”之间的内容是属性。

迭代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.

答案 1 :(得分:0)

没关系...:

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)