猿问

解析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",当 add 时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)

但无法解决'< ... />'.


守着一只汪
浏览 180回答 2
2回答

有只小跳蛙

我看到你发现“'< ... />' 之间的内容”是属性。迭代add元素并检查key属性值的另一种方法是检查谓词中的属性值。例子...蟒蛇import xml.etree.ElementTree as ETtree = 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>&nbsp; &nbsp; <appSettings>&nbsp; &nbsp; &nbsp; &nbsp; <add key="title" value="Donny" />&nbsp; &nbsp; &nbsp; &nbsp; <add key="updaterApplication" value="Updater v4.4" />&nbsp; &nbsp; </appSettings></configuration>

呼如林

没关系...:import xml.etree.ElementTree as ETtree = ET.parse(my_file_name)root = tree.getroot()for elm in root.iter('add'):&nbsp; &nbsp; if elm.attrib['key']=='updaterApplication':&nbsp; &nbsp; &nbsp; &nbsp; elm.attrib['value'] = 'Updater v4.4'&nbsp; &nbsp; print(elm.attrib)
随时随地看视频慕课网APP

相关分类

Python
我要回答