How do i convert an XML document to an array object?

Swarup Roy
Kilo Expert

Hi,

I have the below response from a outbound WS call and i need to convert it into an array (which i will use in a angular script), any pointers what would be the best approach here (checked the XMLHelper, but not sure if that would fit in my case, that's for XML String):

<?xml version="1.0" encoding="UTF-8"?>

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">

<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<GetRes xmlns="urn:TMP:someurn">

<GetResult>

<MyTs>

<MyT>

<name>abc</name>

<date>2016-04-08</date>

<description>desc</description>

</MyT>

</MyTs>

</GetResult>

</GetRes>

</s:Body>

</s:Envelope>

1 ACCEPTED SOLUTION

Geoffrey2
ServiceNow Employee
ServiceNow Employee

So do you need to turn this multi-level object into a multi-dimensional array?   Or do you just need an array of the node values in the MyT node?



This will output: abc, 2016-04-08, desc


var xml = '<?xml version="1.0" encoding="UTF-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetRes xmlns="urn:TMP:someurn"><GetResult><MyTs><MyT><name>abc</name><date>2016-04-08</date><description>desc</description></MyT></MyTs></GetResult></GetRes></s:Body></s:Envelope>';



var helper = new XMLHelper(xml);


var obj = helper.toObject();


var myT = obj['s:Body'].GetRes.GetResult.MyTs.MyT;


var arr = [];


for (key in myT) {


      arr.push(myT[key]+'');


}


gs.log('arr: ' + arr.join(', '));


View solution in original post

3 REPLIES 3

Geoffrey2
ServiceNow Employee
ServiceNow Employee

So do you need to turn this multi-level object into a multi-dimensional array?   Or do you just need an array of the node values in the MyT node?



This will output: abc, 2016-04-08, desc


var xml = '<?xml version="1.0" encoding="UTF-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetRes xmlns="urn:TMP:someurn"><GetResult><MyTs><MyT><name>abc</name><date>2016-04-08</date><description>desc</description></MyT></MyTs></GetResult></GetRes></s:Body></s:Envelope>';



var helper = new XMLHelper(xml);


var obj = helper.toObject();


var myT = obj['s:Body'].GetRes.GetResult.MyTs.MyT;


var arr = [];


for (key in myT) {


      arr.push(myT[key]+'');


}


gs.log('arr: ' + arr.join(', '));


Thanks Geoffrey for your help. I had some issue running it initially though because of some special characters in xmldoc, the method "toObject()" was not able to handle it. However , got rid of it using javascript   and the parsed string worked like a charm.


Thanks Geoffrey. The code snippet helped us!