…thoughts on ServiceNow and digital transformation

Post

Convert a javascript object JSON to XML in ServiceNow


This documentation page states that

The toXMLDoc() method returns JSON provided as XML elements.

however the page does not provide any examples or syntax reference.

I tried my darnedest to get it working but was unsuccessful. Here’s what I tried


var header = {};
header.AuthenticationHeader = 'test';

var output = new XMLHelper().toXMLDoc(JSON.stringify(header));
gs.info(output);
//*** Script: null

var output2 = new XMLHelper().toXMLDoc(header);
gs.info(output2);
//Script: [#document: null]

gs.info(output2.toString());
//Script: [#document: null]

gs.info(typeof(output2));
//*** Script: object

gs.info(JSON.stringify(output2));
//*** Script: {}

Under the hood, the method in the XMLHelper script include looks like this:

    // borrowed and modified from: http://goessner.net/download/prj/jsonxml/json2xml.js
    toXMLDoc : function(o, leaveBlanks) {
       return GlideXMLUtil.parse(this.toXMLStr(o, leaveBlanks));
    },

While there is some documentation for GlideXMLUtil, it doesn’t explain the parse method and this API is probably in Java because I can’t find it in the script includes.

However, the XMLHelper script include also has a toXMLStr method which actually works. Though not documented, this community question provides the syntax:

var bodyObject={testContainer:[{child1: "test"},{child2: "test"},{child3: "test"}]};


var xObject = new XMLHelper().toXMLStr(bodyObject);


var writer=response.getStreamWriter();


writer.writeString(xObject);