Strip XML tags from API response using pm.sendRequest

Hello,

I am writing API responses to a file using pm.sendRequest. I have set up a local server and use the script below which writes the entire XML response to the file as described here: [https://documenter.getpostman.com/view/3407886/RWgp1fB5]

The issue is that I would like to write only the values of the XML tags to the file.

// Convert XML output to JSON format
var jsonObject = xml2Json(responseBody);

//Add Departure Date and Return Date
let departuredate = pm.iterationData.get("DateOut");
let returndate = pm.iterationData.get("DateIn");

// Take care of Envelope and Body tags, grab data and add DateOut and DateIn
var activeStatus = jsonObject['soap:Envelope']['soap:Body'].GetItemTypeStatusResponse.GetItemTypeStatusResult.ItemsStatus.ItemStatus.concat(departuredate).concat(returndate);

// Assigning the extracted value in to a variable
pm.environment.set ("availability", JSON.stringify(activeStatus));

//Log to Console
console.log(['Status '] + pm.environment.get("availability"));

// Write to file
let dataToFile = {
    requestName: request.name || request.url,
    fileExtension: 'CSV',
    responseData: JSON.stringify(activeStatus)  + 'Departure Date: ' + departuredate + ' Return Date: ' + returndate
    };
    
pm.sendRequest({
    url: 'http://localhost:3000/write',
    method: 'POST',
    header: 'Content-Type:application/json',
    body: {
        mode: 'raw',
        raw: JSON.stringify(dataToFile)
    }
}, function(err, res) {
    console.log(res);
});

Is there a way to do this?

I would appreciate any help with this.

Thank you very much.

1 Like

Hi @markus.k,
You can use the library xml2Json that comes with Postman to convert XML to JSON so that you can extract the values from your XML response. For example,

let responseJson = xml2Json(pm.response.text());

responseJson will contain key value pairs of your tags and values.

2 Likes

Hi @bhargavkaranam96,
Thanks very much for your help. I have updated the code accordingly (see above) but the response is [object Object][object Object]. What am I doing wrong?

Hi again @bhargavkaranam96,
I found out I had to stringify the results. :grinning:

The script above works now and writes the API responses (tags and values only) and request parameters to a CSV file and also logs the results to Console in Postman.

Thanks again for your help.