Parsing XML Response In GateWayScript

2.8k views Asked by At

Hi i am new to API connect ... i have a use case where i have to merge responses coming from two endpoints in XML format based on certain conditions.

My flow in the assemble section is like this

1) INVOKE

(i make my first service call and capture the response in a custom 'Response object varibale' -XMLResponse1

2) INVOKE

(i make my second service call and here i am not using any custom 'Response object varibale' Instead i am using apim.getvaribale('message.body') to get the response

3)GATEWAYSCRIPT

Here i want to write my script for parsing the xml and merging the two responses and send back the merged response to the consumer

I observed that the xml response is not getting captured in a custom Response object variable when i try to capture it like below

var test1= apim.getvariable('XMLResponse1'); test1.item(0).childNodes

it throws me an exception like this

test1.item is not a function

now for the second response like below where i am not capturing the response in a custom Response object variable it works well

var test2= apim.getvariable('message.body');

My question:

1)How do i capture the xml responses in a custom Response object variable?

2)How can i parse the response into a javascript object? are there any libraries supported in api connect?

2

There are 2 answers

0
Srikanth Pragallapati On

Below is the samples found from IBM community. Hope this may help you.

**** Sample XML ****

 <Routing>        
    <partner name="Partner A" key="1">
        <from_ID>PartnerA-KEY1-INT</from_ID>
        <to_ID>PartnerA-KEY1-EXT</to_ID>
        <destination>PartnerA-KEY1-DESTINATION</destination>
    </partner>  
    <partner name="Partner B" key="2">
        <from_ID>PartnerB-KEY2-INT</from_ID>
        <to_ID>PartnerB-KEY2-EXT</to_ID>
        <destination>PartnerB-KEY2-DESTINATION</destination>
    </partner>
    <partner name="Partner C" key="3">
        <from_ID>PartnerC-KEY3-INT</from_ID>
        <to_ID>PartnerC-KEY3-EXT</to_ID>
        <destination>PartnerC-KEY3-DESTINATION</destination>
    </partner>  
</Routing>

 **** Corresponing Gateway Script *****

var response = apim.getvariable('XMLResponse1.body');
var objType = response.item(0);
var string  = objType.getElementsByTagName("partner").item(0).getElementsByTagName("from_ID").item(0).textContent;

output ---> string = PartnerA-KEY1-INT

1
Andres Vargas On

Why do you want to merge them in a GatewayScript node??

You could merge them in a mapping node, in wich you have 2 variables as input (refered to the output objects of your invokes) and one XML object as output...

If you have to apply some conditions or comparisons, you could do them in the code part of the mapping nodes

Mapping Node Comparison