The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Parsing through XML document

cnharris1
Kilo Sage

Good morning,

I'm grabbing an XML document through a rest call and that part is working fine.

But when I get the xml document back, I need to parse through the document and grab the customer information, such as their first and last name, phone number, and email. The problem is that there are multiple contacts in the document but the only one that I need to grab is where the contact type = MAIN.  

 

I'm assuming that I would need to loop through all of the contacts to grab the one that I need, which is the MAIN contact.

Would someone be able to assist me in writing the code to grab that information?

Best regards,

 

cnharris1

1 ACCEPTED SOLUTION

Maik Skoddow
Tera Patron
Tera Patron

Hi

to keep it simple I recommend converting the XML payload into JSON. That way it is easier to parse and loop through.

 

See https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0957116 

View solution in original post

5 REPLIES 5

Maik Skoddow
Tera Patron
Tera Patron

Hi

to keep it simple I recommend converting the XML payload into JSON. That way it is easier to parse and loop through.

 

See https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0957116 

Hi Maik, 

Apologies on the late reply. I was out of town due to a family emergency. I've viewed the knowledge article and was able to convert the xml to json but I'm not able to pull out any values for some reason. I'm trying to see if I can at least grab any value in the json payload so that I can begin writing my loop statement. Here's a copy of my code: 


(function execute(inputs, outputs) {
// ... code ...

var res_body = inputs.res_body;
var jsonObj = gs.xmlToJSON(res_body); // Converting XML into a JSON object
var jsonString = JSON.stringify(jsonObj); // Converting JSON object into a String
var jsonObj2 = JSON.parse(jsonString);

//for(var i=0;<jsonObj.

outputs.response2 = jsonObj2[0].SalesOrder.OrderContact.ContactType;
})(inputs, outputs);

Hi Maik,


I asked a partner developer to check out my code and he had to rework my loop statement, but we were finally able to get the information we needed after converting the xml file to JSON. 

Thanks again for the suggestion!

 

Best regards,

cnharris1

Sandeep Rajput
Tera Patron
Tera Patron

@cnharris1 Here is a link to the article covering XML parsing in detail. You can use XPath XML parsing to access the contact type = Main node.

 

Source: https://www.servicenow.com/community/developer-articles/integratenow-chapter-6-working-with-xmls/ta-...