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

Karate框架下如何对XML响应实现指定规则的断言

XML接口响应断言实现方案

你之前尝试直接转JSON失败是因为XML携带命名空间,转换过程极易出现结构冲突生成无效JSON,直接使用XPath做断言是更稳定的方案,不需要做格式转换。

5条校验规则对应的实现逻辑

  • 校验响应的首个标签为Resource:直接判断XML根节点名称即可
  • 校验type值为type1:匹配根节点下type节点的value属性
  • 校验valueTotal值为7:匹配根节点下valueTotal节点的value属性
  • 校验路径/Resource/entry/url对应的值为https://myurl1:匹配第一个entry节点下url节点的value属性(加索引[1]避免多entry节点匹配歧义)
  • 校验深层路径值为CC:匹配第一个entry节点下对应层级code节点的value属性

适配你原有Karate框架的代码示例

你之前使用的* json response = response是Karate框架语法,该框架原生支持XML断言,无需转JSON,直接写如下断言即可:

# 校验根节点为Resource
* match response.name() == 'Resource'
# 校验type值
* match /Resource/type/@value == 'type1'
# 校验valueTotal值
* match /Resource/valueTotal/@value == '7'
# 校验第一个entry的url值
* match /Resource/entry[1]/url/@value == 'https://myurl1'
# 校验深层code值
* match /Resource/entry[1]/resource/user/identifier/type/coding/code/@value == 'CC'

注:Karate已经对XML命名空间做了兼容处理,无需额外处理命名空间前缀即可正常匹配节点。

其他常用工具实现参考

Postman实现

在Postman的Tests标签页写入以下代码:

const xmlDoc = xml2Json(responseBody);
pm.expect(Object.keys(xmlDoc)[0]).to.eql('Resource');
pm.expect(xmlDoc.Resource.type.$.value).to.eql('type1');
pm.expect(xmlDoc.Resource.valueTotal.$.value).to.eql('7');
pm.expect(xmlDoc.Resource.entry[0].url.$.value).to.eql('https://myurl1');
pm.expect(xmlDoc.Resource.entry[0].resource.user.identifier.type.coding.code.$.value).to.eql('CC');

Python + lxml实现

import requests
from lxml import etree

resp = requests.get("你的接口地址")
root = etree.fromstring(resp.content)
# 统一清除命名空间避免匹配异常
for elem in root.getiterator():
    if not isinstance(elem.tag, str):
        continue
    pos = elem.tag.find('}')
    if pos > 0:
        elem.tag = elem.tag[pos+1:]

assert root.tag == 'Resource'
assert root.xpath('./type/@value')[0] == 'type1'
assert root.xpath('./valueTotal/@value')[0] == '7'
assert root.xpath('./entry[1]/url/@value')[0] == 'https://myurl1'
assert root.xpath('./entry[1]/resource/user/identifier/type/coding/code/@value')[0] == 'CC'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:06:05