Created
December 1, 2014 14:30
-
-
Save erickoledadevrel/6b1e9e2796e3c21f669f to your computer and use it in GitHub Desktop.
A function to convert an XML string to a JSON object in Apps Script, using logic similar to the sunset method Xml.parse().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Converts an XML string to a JSON object, using logic similar to the | |
* sunset method Xml.parse(). | |
* @param {string} xml The XML to parse. | |
* @returns {Object} The parsed XML. | |
*/ | |
function xmlToJson(xml) { | |
var doc = XmlService.parse(xml); | |
var result = {}; | |
var root = doc.getRootElement(); | |
result[root.getName()] = elementToJson(root); | |
return result; | |
} | |
/** | |
* Converts an XmlService element to a JSON object, using logic similar to | |
* the sunset method Xml.parse(). | |
* @param {XmlService.Element} element The element to parse. | |
* @returns {Object} The parsed element. | |
*/ | |
function elementToJson(element) { | |
var result = {}; | |
// Attributes. | |
element.getAttributes().forEach(function(attribute) { | |
result[attribute.getName()] = attribute.getValue(); | |
}); | |
// Child elements. | |
element.getChildren().forEach(function(child) { | |
var key = child.getName(); | |
var value = elementToJson(child); | |
if (result[key]) { | |
if (!(result[key] instanceof Array)) { | |
result[key] = [result[key]]; | |
} | |
result[key].push(value); | |
} else { | |
result[key] = value; | |
} | |
}); | |
// Text content. | |
if (element.getText()) { | |
result['Text'] = element.getText(); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment