Skip to content

Instantly share code, notes, and snippets.

@jupegarnica
Created January 9, 2015 16:22
Show Gist options
  • Save jupegarnica/0f46824917ea0732b002 to your computer and use it in GitHub Desktop.
Save jupegarnica/0f46824917ea0732b002 to your computer and use it in GitHub Desktop.
XML to JSON google apps scripts
/**
* 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 XML_to_JSON(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