如何使用 Postman 从 XML 中提取变量?

How do I extract a variable from XML using Postman?

我正在尝试从从 SOAP API 返回的 XML 中提取 SessionId。

我已经通读了 Postman 文档(多次),但它对实现我的目标并不是最有帮助的。

一些博客中的建议是将 XML 转换为 JSON,然后从中提取令牌及其值,但这也无济于事。

我在测试中使用了以下内容:

var jsonObject = xml2Json(responseBody);
postman.setGlobalVariable("Session_Id", jsonObject.SessionID);

上面创建了变量 "Session_Id" 但实际上并没有给它赋值。我很难过。

我肯定是从 API 检索数据,并且可以在 Postman 的 "Body" 响应中查看。

要使用 Postman 从 XML 中提取变量,首先使用 xml2Json 转换器方法将 XML 转换为 JSON:

var responseJson = xml2Json(responseBody);

(其中“responseBody”是您的 xml 正文。) 然后使用console.log方法输出你的JSON数据,如:

console.log(responseJson);

请务必在 Enabling Chrome Dev Tools in Postman

上遵循本教程

在您的测试运行器中,运行 测试,然后右键单击并在运行器中的任意位置“检查”。 Select Chrome 的开发工具启动后的“控制台”选项卡。展开“对象”部分。

然后向下钻取(展开)直到您看到 属性 您需要的数据。 此后,通过将每个向下钻取级别附加到您想要的参数来设置变量:

postman.setGlobalVariable("Session_Id", responseJson.UserSessionToken.SessionID); 

在这种情况下,“responseJson”是对象,“UserSessionToken”是向下钻取的下一级,SessionId 是我在其中需要的参数。

注意:这个答案是postman v7.15.0之前的正确答案。对于此版本之后的版本,已接受的答案可能无效。

自 Postman v7.15.0 以来,接受的答案对我不起作用(在更新之前它曾经是)。您必须将路径段放入方括号中。

例如,在下面的 XML 响应中:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<QuotesPrivateResponse>
    <lease-service>
        <duration-in-months>24</duration-in-months>
    </lease-service>
</QuotesPrivateResponse>

检索值 duration-in-months:

var response = xml2Json(responseBody);
var duration = response["QuotesPrivateResponse"]["lease-service"]["duration-in-months"];
pm.environment.set("duration", duration);

Postman v7.20.1

我想补充一下我的答案,因为上面有几个细节我花了一段时间才解决:

  • 如何处理多部分 SOAP 响应
  • 如何管理 JSON 对象
  • responseBody 定义

这是我对分析的 XML 回复的第一行:

------=_Part_694527_1470506002.1584708814081
Content-Type: application/xop+xml;charset=UTF-8;type="text/xml"
Content-Transfer-Encoding: 8bit
Content-ID: 
<e3bd82ac-d88f-49d4-8088-e07ff1c8d407>
    <?xml version="1.0" encoding="UTF-8" ?>
    <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
        <env:Header/>
        <env:Body>
            <ns2:GenericResponse xmlns:ns2="http://XXXXXXXX">
                <ns2:Service IdcService="XXXXXXXX">
                    <ns2:Document>
                        <ns2:Field name="XXXXXXXX:isSetDefault">1</ns2:Field>
                        <ns2:Field name="XXXXXXXX">CHECKIN_UNIVERSAL</ns2:Field>

在我注意到它是一个多部分之后,我完成了这个 Postman 测试:

var response = pm.response.text();
var responseBody = response.substr(response.indexOf('<env:')); 

pm.test("The body of the response is a valid XML", function () {
     pm.expect(xml2Json(responseBody)).to.exist;
});


pm.test("UCM file upload checkin succesfull", function(){

    var responseJson = xml2Json(responseBody);
    var JsonFields = (responseJson['env:Envelope']['env:Body']['ns2:GenericResponse']['ns2:Service']['ns2:Document']['ns2:Field']);

    JsonFields.forEach( field => {
    if (field.name == 'StatusMessage'){
        console.log("Field = " + field.name);
        pm.expect(field.text().to.include("Successfully checked in"));
        }
    }); 
});