Python etree - 查找完全匹配

Python etree - find exact match

我有以下 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 更改为即:`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)

但我想不通,为什么这个 returns 什么都没有。

在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')

但我不知道如何将其添加到我的示例中。 我不想在这种情况下使用正则表达式。 任何帮助表示赞赏。

您可以使用 XPath 找到特定的 entry 元素。

import xml.etree.ElementTree as ET

tree = ET.parse("sample.xml")   

# Find the element that has a 'key' attribute with a value of 'applications'
entry = tree.find(".//entry[@key='applications']")

# Change the value of the 'value' attribute
entry.set("value", "APP_NAME_2")

tree.write("output.xml")

结果(output.xml):

<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_2" />
      <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>