can we use DOMParser ,to parse XML ?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 04:18 AM
Hi Team,
am using below code to parse incoming XML in script include , but getting error
DOMParser" is not defined.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 06:15 AM
Hi @String ,
you can remove the XMLDocument2 code and use DOMParser to parse the XML instead. Here is an updated code snippet:
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(responseBody, "text/xml");
var resposeStatus = xmlDoc.querySelector("_1_1\\:Status").textContent;
gs.info("price res"+resposeStatus);
if (resposeStatus == 'SUCCESS') {
var count = xmlDoc.getElementsByTagName("ItemNumber").length;
var mrvsArray = [];
for (var i = 0; i < count; i++) {
var mrvs1 = {};
mrvs1.ItemNumber = xmlDoc.getElementsByTagName("ItemNumber")[i].textContent;
mrvs1.amount = xmlDoc.getElementsByTagName("Amount")[i].textContent;
mrvsArray.push(mrvs1);
}
return JSON.stringify(mrvsArray);
}
In the above code used the textContent instead of childNodes[0].nodeValue to extract the text content of each element. This is because textContent is more efficient and reliable than childNodes[0].nodeValue.
Shravan
Please mark this as helpful and correct answer, if this helps you
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 06:28 AM
hi @Sai Shravan thanks for your quick reply ,Still am getting error "DOMParser" is not defined.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 06:31 AM - edited 03-09-2023 06:33 AM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 06:47 AM
Hi @String ,
The error "DOMParser is not defined" usually occurs when the code is being executed outside of a browser environment. ServiceNow runs JavaScript in a server-side context, and the DOMParser is a browser-based API
Can you give a try will below code :
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(responseBody);
var resposeStatus = xmlDoc.getNodeText("//_1_1:Status");
gs.info("price res" + resposeStatus);
if (resposeStatus == 'SUCCESS') {
var count = xmlDoc.getElementsByTagName("ItemNumber").length;
var mrvsArray = [];
for (var i = 0; i < count; i++) {
var mrvs1 = {};
mrvs1.ItemNumber = xmlDoc.getElementsByTagName("ItemNumber")[i].childNodes[0].nodeValue;
mrvs1.amount = xmlDoc.getElementsByTagName("Amount")[i].childNodes[0].nodeValue;
mrvsArray.push(mrvs1);
}
return JSON.stringify(mrvsArray);
}
Shravan
Please mark this as helpful and correct answer, if this helps you