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;
}
One adventure, where are the others?
ReplyDeleteI keep getting an "Authorization is required to perform that action." when I use this code in a Google Sites page.
ReplyDeleteAny ideas as to how to fix it and/or why that would happen?
Thanks
/*
DeleteSteps to application deploy:
1) Save files
2) Run Code.gs > doGet
-> Autorize
3) Run Code.gs > doGet (newly)
-> Check for errors
3) Create new version: File > Manage versions
4) Public > Deploy web aplication...
-> Use the new version
5) Copy the link and access it
Note: I use the interface in portuguese...
*/