Using POST request in Postmat I received a body response as XML data like this.
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getAuthenticationTokenResponse xmlns:ns2="http://some_url.com" xmlns:ns3="http://some_url.com">
<return>111222333</return>
</ns2:getAuthenticationTokenResponse>
</S:Body>
</S:Envelope>
And I need to get somehow value 111222333 as a collection variable. And I’m lost with solution since I have no experience with JS before. Please provide me with some solution.
2
maybe xml2js
can resolve your question.
this is sample code:
const xml2js = require('xml2js');
xml2js.parseString(pm.response.text(), function (err, result) {
console.log(result);
});
1
xml2js is available in the Postman sandbox and gives you a lot more control over the output.
You are basically converting the XML to a JavaScript Object.
For example…
// step 1 - parse XMLSoap response
const xmlResponse = pm.response.json();
// step 2 - parse the XML test to JSON - so its easier to work with
let parseString = require('xml2js').parseString;
const stripPrefix = require('xml2js').processors.stripPrefix;
parseString(xmlResponse, {
tagNameProcessors: [stripPrefix],
ignoreAttrs: true,
explicitArray: false,
}, function (err, jsonData) {
// handle any errors in the XML
if (err) {
console.log(err);
} else {
// do something with the result
console.log(jsonData.Envelope.Body.getAuthenticationTokenResponse.return); // 111222333
}
});
It depends on how complex your XML is, but have a look here (scroll to the bottom) for all of the formatting options.
https://www.npmjs.com/package/xml2js
2
Just enter “111222333” into your collection variable
1
I’m really appreciate for all who give me help with this topic. Final version of solution is looks like this:
> const xml2js = require('xml2js'); console.log(xml2js);
>
> // taking XML response
> const responseBody = pm.response.text();
> console.log(responseBody);
>
> //parsing XML body
> xml2js.parseString(responseBody, { explicitArray:
> false }, (err, result) => {
> if (err) {
> console.error("Error parsing XML:", err);
> } else {
> //Taking Token
> const tokenValue = result['S:Envelope']['S:Body']['ns2:getAuthenticationTokenResponse']['return'];
> console.log(tokenValue);
>
> // Bringing Token to a collection variable
> pm.collectionVariables.set("a_Token", tokenValue);
> console.log("Extracted Token Value: ", tokenValue);
> } });