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

如何在Karate框架中从特殊格式XML响应提取correlationID

从SOAP API的MIME响应中提取correlationId

我们调用SOAP API后得到如下模拟响应:

* def response = 
--uuid:123456
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml"
Content-Transfer-Encoding: binary
Content-ID: <root.message@cxf.apache.org>

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

<soap:Header>
  <m:Trans xmlns:m="https://www.w3schools.com/transaction/"
  soap:mustUnderstand="1">234
  </m:Trans>
</soap:Header>
<success>true</success>
<correlationId>123456abcd</correlationId>
...
...
</soap:Envelope>
--uuid:123456--

需要提取<correlationId>标签的值123456abcd,尝试过以下正则替换方法但无效:

  • def corrId = response.replace(/.*([^<]+)<\/correlationId>.*/, '$1')

解决方案

方法1:使用Karate内置XML解析(推荐)

你的代码是Karate脚本,Karate原生支持XML解析,无需依赖正则。步骤如下:

// 1. 提取MIME响应中的XML部分,去除边界和头部
* def xmlContent = response.replaceAll('(?s)^--uuid:.*?\n\n(.*)--uuid:.*?$', '$1')
// 2. 用XPath定位并提取correlationId的值
* def corrId = karate.xmlPath(xmlContent, '$..correlationId')
  • (?s)开启单行模式,让正则可以匹配跨多行的内容
  • $..correlationId是XPath表达式,直接定位所有correlationId节点并返回对应值

方法2:修复正则表达式

如果一定要用正则,需处理换行和空白问题,调整后的正则如下:

* def corrId = response.replaceAll('(?s).*<correlationId>([^<]+)</correlationId>.*', '$1')
  • (?s)确保正则能匹配换行符,覆盖响应中的多行内容
  • 明确匹配<correlationId>标签,避免其他标签干扰

方法3:直接解析Karate响应

如果这是Karate调用API后的原始响应,可直接通过response.body获取XML对象后提取:

// 直接通过对象属性访问
* def corrId = response.body.Envelope.correlationId
// 或用XPath定位文本节点
* def corrId = karate.xpath(response.body, '//correlationId/text()')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:42:18