Search code examples
xmlpostmanpostman-pre-request-script

How to set global variable from XML response


Im trying to set global variable sessionId from the XML response. I tried below code:

var responseJson = xml2Json(responseBody);
console.log(responseJson);
postman.setEnvironmentVariable("sessionID", responseJson.Envelope.Body.CreateSessionResponse.CreateSessionResult.Output.sessionID);

But its returning error:

TypeError: Cannot read properties of undefined (reading 'Body').

Heres how the JSON structure looks like from the response XML:

Please click on this image to see the json structure

Here is my response XML:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <CreateSessionResponse xmlns="http://vz.com/Anywhere/Service/v9">
            <CreateSessionResult>
                <output>
                    <sessionId>azrsit-2fb658dc-7048-4188-8427</sessionId>
                </output>
            </CreateSessionResult>
        </CreateSessionResponse>
    </s:Body>
</s:Envelope>

Solution

  • Option 1. Using xml2Json and bracket notation to target the elements due to some of the elements using special characters.

    let responseJson = xml2Json(responseBody);
    
    let sessionId = responseJson["s:Envelope"]["s:Body"]["CreateSessionResponse"]["CreateSessionResult"]["output"]["sessionId"];
    
    console.log(sessionId);
    

    If you struggle to target an element, start at the top and console log it one level at at time until you hit the intended target.

    Option 2. Using xml2js to remove all of the name space info, making it easier to target the elements.

    let respBodyXML = pm.response.text();
    let parseString = require('xml2js').parseString;
    let stripPrefix = require('xml2js').processors.stripPrefix;
    
    parseString(respBodyXML, {
        tagNameProcessors: [stripPrefix], //removing prefix
        ignoreAttrs: true, //ignoring all attributes including xmlns
        explicitArray: false,
        explicitRoot: true//including root tag inside the JSON
    }, function (err, result) {
        console.log(result);
        console.log(result.Envelope.Body.CreateSessionResponse.CreateSessionResult.output.sessionId);
    });
    

    enter image description here