分析xml类型fi

2024-05-29 03:34:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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"。你知道吗

我试过:

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)

但无法处理'< ... />'之间的内容。你知道吗


Tags: keyaddtreevaluerootxmlconfigurationet
2条回答

我看到你发现“内容之间”<。。。/>;''是属性。你知道吗

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

没关系。。。地址:

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)

相关问题 更多 >

    热门问题