get XML element attribute when value of sibling attribute is particular value using elementtree

Viewed 34

I have an XML file similar to below:

<data>
    <ruleset>
        <ruleset_mapping>
            <rule id="foo" />
            <action cd_result="Pass" fg_continue="No" fg_disable="0">
                <cd_alert>foo</cd_alert>
                <id_outcome>APPROVE</id_outcome>
                <tx_message_application />
            </action>
            <cd_level>Application</cd_level>
        </ruleset_mapping>
        <ruleset_mapping>
            <rule id="bar" />
            <action cd_result="Fail" fg_continue="No" fg_disable="0">
                <cd_alert>bar</cd_alert>
                <id_outcome />
                <tx_message_application />
            </action>
            <cd_level>Application</cd_level>
        </ruleset_mapping>
    </ruleset>
</data>

I want to extract the value of the cd_result attribute from the action element, but only where the value of the id attribute in the sibling rule element is foo.

So, in the above, I want to get the value Pass. I think the result should be found using something similar to:

for element in root.findall(".//ruleset_mapping/rule"):
    if element.attrib['id'] == 'foo':
        print(root.findall(".//ruleset_mapping/action['@cd_result']"))

...but I cannot get it quite right. Can anyone help?

1 Answers

Here is a way to do it. Iterate over the ruleset_mapping elements.

for rs_map in root.findall(".//ruleset_mapping"):
    rule_id = rs_map.find("rule").get("id")
    cd_result = rs_map.find("action").get("cd_result")
                         
    if rule_id == "foo":
        print(cd_result)
Related