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

如何在Jenkins Pipeline Groovy中提取XML的testcase标签name属性到数组

在Jenkins Pipeline Groovy脚本中提取XML所有testcase的name属性值

问题场景

你有如下XML测试报告文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testsuites>
  <testsuite name="xray" tests="2" failure="0" timestamp="2023-07-07T05:25:33.339Z" skipped="0" failure-evaluating="0">
    <testcase name="SPT-4323" classname="testim.io.test" time="52.597" ownedBy="Staysure Automation" ownerEmail="automationteam@staysure.co.uk">
      <system-out>https://app.testim.io/#/project/9GScC/branch/master/test/ZKkR</system-out>
    </testcase>
    <testcase name="SPT-4331" classname="testim.io.test" time="20.823" ownedBy="Automation Team" ownerEmail="nipunam@intervest.lk">
      <system-out>https://app.testim.io/#/project/9GScCU/branch/master/test/7O9a</system-out>
    </testcase>
  </testsuite>
</testsuites>

需要在Jenkins Pipeline的Groovy脚本中,将所有<testcase>标签的name属性值提取到数组中(testcase数量不固定),期望得到类似Test_IDS : ["SPT-4323", "SPT-4331"]的结果。

你尝试的代码无法输出任何值:

def File = readFile "${env.WORKSPACE}/testim-tests-report.xml"
echo "${File}"
def xml = new XmlSlurper().parseText(File)
def xrayID = xml.testsuites.testsuite.testcase[1].@name

echo "Xray ID is ${xrayID}"

问题原因

你的代码存在两个关键问题:

  • 使用XmlSlurper.parseText()解析后,返回的根节点已经是<testsuites>,所以不需要再通过xml.testsuites访问,直接使用xml.testsuite即可
  • 你只获取了索引为1的单个testcase的name属性,没有遍历所有testcase标签

解决方案

以下是修正后的Groovy脚本,能够提取所有testcase的name属性到数组:

// 读取XML文件
def xmlContent = readFile "${env.WORKSPACE}/testim-tests-report.xml"
// 解析XML
def xml = new XmlSlurper().parseText(xmlContent)
// 提取所有testcase的name属性,收集到数组
def testIds = xml.testsuite.testcase.collect { it.@name.text() }
// 输出结果
echo "Test_IDS : ${testIds}"

代码说明

  • XmlSlurper解析XML后,根节点对应<testsuites>,因此直接通过xml.testsuite访问子节点
  • 使用collect()方法遍历所有<testcase>节点,通过it.@name.text()获取每个节点的name属性文本值,最终返回一个字符串数组
  • 无论XML中有多少个testcase标签,这段代码都能自动收集所有name属性值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:32:36