简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM