XMLHelper

The XML helper script include makes it extremely easy to parse XML in ServiceNow JavaScript.

The script include will convert your XML document into a JavaScript object.

The following changes were made to the XML helper script include:
  • The toObject() method now returns an object whose properties are all JavaScript objects. This method now works properly whether the supplied parameter is an XML document or an XML string.
  • The methods toXMLDoc() and toXMLStr() are now available. These methods are the inverse of the existing toObject() method.
  • The toObject() method has been extended to take an optional parameter of the XML input to convert as an alternative to the (still present) mechanism of specifying the XML input in the constructor.

Example

The following example takes an example XML document and then converts it into a JavaScript object. It then takes the outputted JavaScript object and uses a recursive function to output all members of the object. The recursive function is useful and reusable if you have any questions about how a particular XML document will be structured after being converted to a JavaScript object.

Script

var xmlString ="<company>"+"<employee>"+"<id>10</id>"
     +"<firstname>Tom</firstname>"+"<lastname>Cruise</lastname>"
     +"<test>test1</test>"+"<test>test3</test>"+"</employee>"
     +"<employee>"+"<id>20</id>"+"<firstname>Paul</firstname>"
     +"<lastname>Enderson</lastname>"+"<test>test6</test>"
     +"<test>test5</test>"+"</employee>"+"<employee>"+"<id>30</id>"
     +"<firstname>Paul</firstname>"+"<lastname>Bush</lastname>"  
     +"<test>test2</test>"+"<test>test4</test>"+"</employee>"+"</company>"; 
 
var helper =new XMLHelper(xmlString);
var obj = helper.toObject();
 
logObj(obj,"*")function logObj(obj, sep){
             for(x in obj){
               if(typeof obj[x]!="function"){
                   gs.log(sep + x +":: "+ obj[x]);}
               logObj(obj[x], sep +"*");}}

Output

*** Script: *employee:: [object Object],[object Object],[object Object]
*** Script: **2:: [object Object]
*** Script: ***id:: 30
*** Script: ***test:: test2,test4
*** Script: ****0:: test2
*** Script: ****1:: test4
*** Script: ***firstname:: Paul
*** Script: ***lastname:: Bush
*** Script: **0:: [object Object]
*** Script: ***id:: 10
*** Script: ***test:: test1,test3
*** Script: ****0:: test1
*** Script: ****1:: test3
*** Script: ***firstname:: Tom
*** Script: ***lastname:: Cruise
*** Script: **1:: [object Object]
*** Script: ***id:: 20
*** Script: ***test:: test6,test5
*** Script: ****0:: test6
*** Script: ****1:: test5
*** Script: ***firstname:: Paul
*** Script: ***lastname:: Enderson