Sometimes it makes sense to create JSON out of XML. A perfect example is when the xmlElement object in Google Apps Script fails to support nested elements (bug has been filed and is being fixed according to Google).
Google Apps Script also supports XML Shorthand aka JSON. To convert your XML to JSON, feel free to use this piece of code (thanks to @TinusOZ for some critical fixes in the code).
var kv;
function parseXMLToShortHand(xmlElement){
var result = "";
var children = xmlElement.getElements();
var childrenShortHand = "";
if(children == "")
{
if(xmlElement.getText() != "")
{
childrenShortHand = "\""+xmlElement.getText() + "\"";
}
}else{
for(var i = 0; i < children.length; i++)
{
childrenShortHand += parseXMLToShortHand(children[i]);
if(i < children.length - 1)
{
childrenShortHand += ",";
}
}
}
var attribs = xmlElement.getAttributes();
var attribsShortHand = "";
for(var i = 0; i < attribs.length; i++)
{
attribsShortHand += "{\"" + attribs[i].getName().getLocalName() + "\":\"" + attribs[i].getValue() + "\"}";
//check if Key/Value pair object is available
if(kv==null){
kv=new Object();
}
//Set the current namespace to the Key/Value pair for reference
kv[attribs[i].getValue()]=attribs[i].getName().getLocalName();
if(i < attribs.length - 1)
{
attribsShortHand += ",";
}
}
//resolve namespaces from KV pair
elementName = xmlElement.getName().getLocalName();
if(xmlElement.getName().getNamespace()!=""){
elementName= (kv[xmlElement.getName().getNamespace()])+":"+elementName;
}
if(attribsShortHand == "")
{
childrenShortHand = "[\"" + elementName + "\"," + childrenShortHand + "]";
}else{
if(childrenShortHand==""){
childrenShortHand = "[\"" + elementName + "\","+ attribsShortHand +"]";
}else{
childrenShortHand = "[\"" + elementName + "\","+ attribsShortHand + "," + childrenShortHand + "]";
}
}
return childrenShortHand;
}