Attempting to save variable from XML to no avail

Firstly, being complete up front, I am a novice when it comes to utilising APIs (only started playing around a couple of weeks ago).

The APIs that I need to use regularly require a session key, which expires pretty fast if you are not actively using, and so I was hoping to store that key as a variable in my collection so I could build out calls that are regularly used and put the variable in to save copy/paste time.

However, I don’t seem to be able to get the variable to save in the correct format. I have attached a picture below to show what this looks like but basically the response for the session key request is;

<response status="success">
   <value type="string">4whOJWwMi1OfXRybTzWn7ANDZi43Vee3CCfqJY9cUUk.</value>

I have attempted to pop that into a variable by first converting to JSON object, then pulling out the session key and finally saving it as a variable. However, the script below doesn’t seem to take the value on its own and save it as a string that I can reuse but rather stores it as some kind of object.

var jsonObject = xml2Json(responseBody);
var key = jsonObject.response.value;
pm.collectionVariables.set("dans-session-key", jsonObject.response.value);

Kinda out of my depth here and would appreciate a steer.

Try this;

var jsonObject = xml2Json(responseBody);

//Locate value
var key = jsonObject.response.value;
console.log("key = ", key);

//Get and Set
pm.collectionVariables.set("DansSessionKey", key['_']);
console.log("DansSessionKey = ", pm.collectionVariables.get("DansSessionKey"));

Thanks for replying, I actually managed to figure this out by adding ._ when grabbing the value out as I didn’t realise but the ‘value’ attribute had two children (being ‘_’ and ‘$’).

var jsonObject = xml2Json(responseBody);
pm.collectionVariables.set(“dans-session-key”, jsonObject.response.value._);

1 Like