我有以下 xml 文件:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE TaskDefinition PUBLIC "xxx" "yyy">
<TaskDefinition created="time_stamp" formPath="path/sometask.xhtml" id="sample_id" modified="timestamp_b" name="sample_task" resultAction="Delete" subType="subtype_sample_task" type="sample_type">
<Attributes>
<Map>
<entry key="applications" value="APP_NAME"/>
<entry key="aaa" value="true"/>
<entry key="bbb" value="true"/>
<entry key="ccc" value="true"/>
<entry key="ddd" value="true"/>
<entry key="eee" value="Disabled"/>
<entry key="fff"/>
<entry key="ggg"/>
</Map>
</Attributes>
<Description>Description.</Description>
<Owner>
<Reference class="sample_owner_class" id="sample_owner_id" name="sample__owner_name"/>
</Owner>
<Parent>
<Reference class="sample_parent_class" id="sample_parent_id" name="sample_parent_name"/>
</Parent>
</TaskDefinition>
我要搜索:
<entry key="applications" value="APP_NAME"/>
并将其更改value
为 ie.: `APP_NAME_2.
我知道我可以通过这个提取这个值:
import xml.etree.cElementTree as ET
tree = ET.ElementTree(file='sample.xml')
root = tree.getroot()
print(root[0][0][0].tag, root[0][0][0].attrib)
但在这种情况下,我必须知道条目在树中的确切位置 - 所以它不灵活,我不知道如何更改它。
还尝试过这样的事情:
for app in root.attrib:
if 'applications' in root.attrib:
print(app)
但我不知道,为什么这什么也没返回。
在 python 文档中,有以下示例:
for rank in root.iter('rank'):
new_rank = int(rank.text) + 1
rank.text = str(new_rank)
rank.set('updated', 'yes')
tree.write('output.xml')
但我不知道如何将其添加到我的示例中。我不想在这种情况下使用正则表达式。任何帮助表示赞赏。