You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ElementTree获取特定兄弟属性对应的XML元素属性

提取特定条件下的XML属性值

需求:提取action元素的cd_result属性值,但仅当同级rule元素的id属性为foo时(示例中预期结果为Pass)。

示例XML内容

<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>

尝试的错误代码

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

解决方法

方法1:遍历父节点筛选

先定位所有ruleset_mapping节点,逐个检查内部的rule是否符合条件,再获取同级的action属性:

import xml.etree.ElementTree as ET

tree = ET.parse("your_xml_file.xml")
root = tree.getroot()

for mapping in root.findall(".//ruleset_mapping"):
    rule = mapping.find("rule")
    # 检查rule存在且id为foo
    if rule and rule.attrib.get("id") == "foo":
        action = mapping.find("action")
        if action:
            print(action.attrib.get("cd_result"))

方法2:使用XPath直接定位(更高效)

利用XPath的条件表达式,直接定位到符合要求的action元素:

import xml.etree.ElementTree as ET

tree = ET.parse("your_xml_file.xml")
root = tree.getroot()

# XPath语法:找到包含id为foo的rule的ruleset_mapping,再取其下的action
action = root.find(".//ruleset_mapping[rule/@id='foo']/action")
if action:
    print(action.attrib.get("cd_result"))

错误代码问题说明

  1. 全局查找action:代码中用root.findall会遍历整个XML,无法限定到当前rule所在的ruleset_mapping父节点,导致匹配所有action。
  2. XPath语法错误:action['@cd_result']写法不正确,获取属性应使用action/@cd_result,但核心问题是缺少父节点的条件限定。

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:31:17