如何在Postman中解析XML响应体并设置为集合变量
在Postman中从XML响应提取值并设置为集合变量
方法1:使用Postman内置XML转JSON工具(推荐)
这种方法适配XML结构,稳定性更高:
- 打开你的POST请求,切换到Tests标签页
- 粘贴以下代码:
// 读取XML响应文本并转换为JSON对象 const xmlText = pm.response.text(); const jsonData = xml2Json(xmlText); // 按XML层级提取token值 const authToken = jsonData['S:Envelope']['S:Body']['ns2:getAuthenticationTokenResponse']['return']; // 设置为集合变量(可替换"auth_token"为你需要的变量名) pm.collectionVariables.set("auth_token", authToken);
方法2:使用正则表达式提取(适合结构固定的场景)
如果XML结构不会变动,也可以用正则直接匹配目标值:
- 同样在请求的Tests标签页,粘贴代码:
// 匹配<return>标签内的内容 const matchResult = pm.response.text().match(/<return>(.*?)<\/return>/); if (matchResult) { const authToken = matchResult[1]; pm.collectionVariables.set("auth_token", authToken); }
验证变量是否设置成功
点击Postman右上角的眼睛图标(查看变量),在集合变量列表中就能看到auth_token,值应为111222333。
内容的提问来源于stack exchange,提问作者Nat S
相关产品推荐
相关产品推荐

