Skip to content

Instantly share code, notes, and snippets.

@pmgupte
Created January 9, 2018 07:14
Show Gist options
  • Save pmgupte/9887a7dc298d7cf6e3674629b54f73f5 to your computer and use it in GitHub Desktop.
Save pmgupte/9887a7dc298d7cf6e3674629b54f73f5 to your computer and use it in GitHub Desktop.
Sample Servicenow script showing how to handle case of non existing XML tag.
/*
* Checks if given node indeed of given tag.
* Params:
* tag - String, name of tag to check
* node - XMLNode, node in which to check for the tag
* Returns:
* true, if tag is present
* false, otherwise
*/
function isNodeOfTag (node, tag) {
try {
if (tag == node.getNodeName()) {
gs.info("Given node indeed belongs to tag " + tag);
return true;
}
} catch (error) {
gs.error("Given node might not belong to tag " + tag + ". Error while checking: " + error);
return false;
}
}
var xmlString = "<test>" +
" <one>" +
" <two att=\"xxx\">abcd1234</two>" +
" <three boo=\"yah\" att=\"yyy\">1234abcd</three>" +
" <two>another</two>" +
" </one>" +
" <number>1234</number>" +
"</test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);
var node = xmlDoc.getNode("/test/one/two"); // tag 'two' is present in this XML.
isNodeOfTag(node, "two");
var node = xmlDoc.getNode("/test/one/four"); // tag 'four' is not present in this XML.
isNodeOfTag(node, "four");
Given node indeed belongs to tag two
Given node might not belong to tag four. Error while checking: java.lang.NullPointerException
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment