soappostman

Is it possible to separate and wrap variables with <arr:int> in Postman?


Attempting to POST a SOAP request in Postman. If a list of collection variables is provided, is it possible to separate the variables and wrap them in arr:int using JavaScript?

For example:

In Postman, a collection variable called productId which has three values; 123, 456, 789 is set.

The raw body of the request is set as follows:

<v1:ProductId>{{productId}}</v1:ProductId>

After the pre-script has run, the request should be modified to look like the below:

<v1:ProductId>`
<arr:int>123</arr:int>
<arr:int>456</arr:int>
<arr:int>789</arr:int>
</v1:ProductId>

I noticed this post ($xml) which looked promising, I'm just wondering if $xml is still the best solution given this question was raised nine years ago and also, the number of values that might be used isn't static, I've used three in my example, but it's possible that any number of values might be used.


Solution

  • Yes, this is totally doable with a pre-request script. Here's what you need (or similar):

    This script takes your comma-separated IDs, splits them, and wraps each one in the XML tags you need. Works with any number of IDs, not just three.

    Put this in your pre-request script tab and adapt as you see fit. I don't know the rest of the context where this is used, so this is my best guess.

    // Grab the current request body and your list of IDs
    let body = pm.request.body.raw;
    let idList = pm.collectionVariables.get("productId").split(",").map(id => id.trim());
    
    // Build the replacement text
    let newContent = "<v1:ProductId>\n";
    idList.forEach(id => {
        newContent += `<arr:int>${id}</arr:int>\n`;
    });
    newContent += "</v1:ProductId>";
    
    // Replace the placeholder with our new content
    body = body.replace("<v1:ProductId>{{productId}}</v1:ProductId>", newContent);
    
    // Update the request
    pm.request.body.raw = body;