Unable to Iterate through xml response and and update the existing record(s)

jitusingh
Tera Contributor

Hi Everyone, 

 

I am stuck while parsing the xml response. 

Xml Resonse = 

RESPONSE

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<POSServices xmlns="http://pos.odc.vzwcorp.com">

    <ServiceHeader>

        <userName>CETOMPOS</userName>

        <password>*********</password>

        <clientAppName>ATG-ECOM-DESK</clientAppName>

        <clientAppUserName>ECOM</clientAppUserName>

        <serviceName>inventoryLookup</serviceName>

        <serviceAction>retrieveItemQuantityByLocation</serviceAction>

        <applicationResponseCode>99000</applicationResponseCode>

        <applicationResponseClass>SUCCESS</applicationResponseClass>

        <applicationResponseMessage>[Wsrv15:vipsvcs06:06]Transaction processed successfully.</applicationResponseMessage>

        <applicationResponseDetails></applicationResponseDetails>

        <timeStamp>2025-02-17T17:30:08.879-05:00</timeStamp>

        <storeID>0</storeID>

        <clientAddlInfo>900000011</clientAddlInfo>

        <clientReferenceNumber>900000011</clientReferenceNumber>

        <transactionId>89885_1</transactionId>

        <sessionID>89885</sessionID>

        <serviceAreaZip>30329</serviceAreaZip>

        <clientOrderInfo>

            <channelId>B2C</channelId>

            <vendorId>VZWCOM</vendorId>

            <clientOrderType></clientOrderType>

        </clientOrderInfo>

        <responseFormat>XML</responseFormat>

        <atgCartId></atgCartId>

        <loggingId>c4ea7a390135aae5</loggingId>

    </ServiceHeader>

    <ServiceBody>

        <bulkItem>

            <response>

                <itemCodes>

                    <itemCount>3</itemCount>

                    <item>

                        <quantity>12</quantity>

                        <itemCode>OCPO3MAPL13128GN</itemCode>

                        <quantityAllocated>0</quantityAllocated>

                    </item>

                    <item>

                        <quantity>266</quantity>

                        <itemCode>OCPO3MAPL13128PK</itemCode>

                        <quantityAllocated>0</quantityAllocated>

                    </item>

                    <item>

                        <quantity>98</quantity>

                        <itemCode>RTSAMS901128K</itemCode>

                        <quantityAllocated>0</quantityAllocated>

                    </item>

                </itemCodes>

            </response>

        </bulkItem>

    </ServiceBody>

</POSServices>




I tried using the below code to parse the response in the flow action script step


   
    (function execute(inputs, outputs) {

    var xmlResponse = inputs.responseBody;
    var xmlDoc = new XMLDocument(xmlResponse);

    var items = xmlDoc.getNodes('POSServices/ServiceBody/bulkItem/response/itemCodes/item');
    var itemCount = items.getLength();  

    gs.info('Total items found: ' + itemCount+'   '+items);  
   
    if (itemCount > 0) {
        for (var i = 0; i < itemCount; i++) {
            var item = items.item(i);
           
            if (item) {
                var itemCode = item.getNodeText('itemCode');
                var quantity = item.getNodeText('quantity');
                var hardwareModelGR = new GlideRecord('cmdb_hardware_product_model');  
                hardwareModelGR.addEncodedQuery('model_number=' + itemCode);
                hardwareModelGR.query();
 
                // Check if record exists and update
                if (hardwareModelGR.next()) {
                    hardwareModelGR.u_item_quantity = quantity; // Update the quantity field
                    try {
                        var updateResult = hardwareModelGR.update();  // Update the record
            if (updateResult) {
                            outputs.updatestatus = 'Record updated successfully for item code: ' + itemCode;
                        } else {
                            outputs.updatestatus = 'Failed to update the record for item code: ' + itemCode + '. Check permissions or field restrictions.';
                        }
                    } catch (e) {
                        outputs.updatestatus = 'Error updating record for item code: ' + itemCode + '. Error: ' + e.message;
                    }
                } else {
                    outputs.updatestatus = 'Record not found for item code: ' + itemCode;
                }
            } else {
                gs.info('item is null or undefined'+i);
            }
        }
    } else {
        outputs.updatestatus = 'No items found in the response.';
    }
})(inputs, outputs);


I am getting the itemCount but  'var item = items.item(i);' returns null value. Therefore unable to fetch the item details.
This is where I am stuck right now

Can anyone help me on this
1 ACCEPTED SOLUTION

Vishal Jaswal
Giga Sage

Hello @jitusingh 

Better to convert xml to JSON and it will be way too easier for you to get the desired results:

Background Script:

// XML response as a variable

var xmlResponse = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<POSServices xmlns="http://pos.odc.vzwcorp.com">
<ServiceHeader>
<serviceName>inventoryLookup</serviceName>
</ServiceHeader>
<ServiceBody>
<bulkItem>
<response>
<itemCodes>
<itemCount>3</itemCount>
<item>
<quantity>12</quantity>
<itemCode>OCPO3MAPL13128GN</itemCode>
</item>
<item>
<quantity>266</quantity>
<itemCode>OCPO3MAPL13128PK</itemCode>
</item>
<item>
<quantity>98</quantity>
<itemCode>RTSAMS901128K</itemCode>
</item>
</itemCodes>
</response>
</bulkItem>
</ServiceBody>
</POSServices>`;

// Remove namespace  before converting XML to JSON
xmlResponse = xmlResponse.replace(/xmlns="[^"]+"/g, '');
// Convert XML to JSON

var jsonPayload = gs.xmlToJSON(xmlResponse);
gs.info("Converted JSON: " + JSON.stringify(jsonPayload, null, 2));

// Navigate the JSON structure
var items = jsonPayload.POSServices.ServiceBody.bulkItem.response.itemCodes.item;

// Ensure items exist
if (!items) {
    gs.error("No items found in JSON payload.");
} else {

    // scenario where there is a single item
    if (!Array.isArray(items)) {
        items = [items]; // Convert to an array
    }
    gs.info("Total items found: " + items.length);

    // Loop through items and print details
    for (var i = 0; i < items.length; i++) {
        var itemCode = items[i].itemCode;
        var quantity = items[i].quantity;
        gs.info("Processing Item Code: " + itemCode + ", Quantity: " + quantity);
    }
} 


Results:

vishal_jaswal_0-1742406095222.png

 


Hope that helps!

View solution in original post

1 REPLY 1

Vishal Jaswal
Giga Sage

Hello @jitusingh 

Better to convert xml to JSON and it will be way too easier for you to get the desired results:

Background Script:

// XML response as a variable

var xmlResponse = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<POSServices xmlns="http://pos.odc.vzwcorp.com">
<ServiceHeader>
<serviceName>inventoryLookup</serviceName>
</ServiceHeader>
<ServiceBody>
<bulkItem>
<response>
<itemCodes>
<itemCount>3</itemCount>
<item>
<quantity>12</quantity>
<itemCode>OCPO3MAPL13128GN</itemCode>
</item>
<item>
<quantity>266</quantity>
<itemCode>OCPO3MAPL13128PK</itemCode>
</item>
<item>
<quantity>98</quantity>
<itemCode>RTSAMS901128K</itemCode>
</item>
</itemCodes>
</response>
</bulkItem>
</ServiceBody>
</POSServices>`;

// Remove namespace  before converting XML to JSON
xmlResponse = xmlResponse.replace(/xmlns="[^"]+"/g, '');
// Convert XML to JSON

var jsonPayload = gs.xmlToJSON(xmlResponse);
gs.info("Converted JSON: " + JSON.stringify(jsonPayload, null, 2));

// Navigate the JSON structure
var items = jsonPayload.POSServices.ServiceBody.bulkItem.response.itemCodes.item;

// Ensure items exist
if (!items) {
    gs.error("No items found in JSON payload.");
} else {

    // scenario where there is a single item
    if (!Array.isArray(items)) {
        items = [items]; // Convert to an array
    }
    gs.info("Total items found: " + items.length);

    // Loop through items and print details
    for (var i = 0; i < items.length; i++) {
        var itemCode = items[i].itemCode;
        var quantity = items[i].quantity;
        gs.info("Processing Item Code: " + itemCode + ", Quantity: " + quantity);
    }
} 


Results:

vishal_jaswal_0-1742406095222.png

 


Hope that helps!