Created
January 9, 2018 07:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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