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

Karate XML解析:提取状态为Active的行的指定列值

XML数据提取解决方案

以下是两种实用的方法来提取符合条件的数据:

方法一:Python内置库遍历解析

直接遍历XML节点,筛选出index="1"列值为Active的行,再提取对应行的index="0"列值:

import xml.etree.ElementTree as ET

# 替换为你的XML数据(或从文件读取)
xml_content = '''<Batch>
    <results>
        <columns>
            <column index="0">Sample Batch ID</column>
            <column index="1">Status</column>
            <column index="2">GSA-48v4-0</column>
        </columns>
        <rows>
            <row index="0">
                <column index="0">102</column>
                <column index="1">Completed</column>
                <column index="2">GSA-48v4-0</column>
            </row>
            <row index="1">
                <column index="0">102</column>
                <column index="1">Active</column>
                <column index="2">GSA-48v4-0</column>
            </row>
        </rows>
    </results>
</Batch>'''

root = ET.fromstring(xml_content)
target_ids = []

# 遍历所有行节点
for row in root.findall('.//row'):
    status = None
    batch_id = None
    # 遍历当前行的所有列
    for col in row.findall('column'):
        col_index = col.get('index')
        if col_index == '1':
            status = col.text
        elif col_index == '0':
            batch_id = col.text
    # 判断状态是否符合条件
    if status == 'Active':
        target_ids.append(batch_id)

print(target_ids)  # 输出: ['102']

方法二:XPath条件筛选(更简洁)

利用XPath的条件表达式直接定位目标节点,一步完成筛选:

import xml.etree.ElementTree as ET

xml_content = '''<Batch>
    <results>
        <columns>
            <column index="0">Sample Batch ID</column>
            <column index="1">Status</column>
            <column index="2">GSA-48v4-0</column>
        </columns>
        <rows>
            <row index="0">
                <column index="0">102</column>
                <column index="1">Completed</column>
                <column index="2">GSA-48v4-0</column>
            </row>
            <row index="1">
                <column index="0">102</column>
                <column index="1">Active</column>
                <column index="2">GSA-48v4-0</column>
            </row>
        </rows>
    </results>
</Batch>'''

root = ET.fromstring(xml_content)
# XPath表达式:匹配包含"Active"状态的行,提取对应ID列
target_ids = [col.text for col in root.findall('.//row[column[@index="1" and text()="Active"]]/column[@index="0"]')]

print(target_ids)  # 输出: ['102']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:21:03