Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @OnlyCurrentDoc
- */
- function getXmlData(url, user, pass) {
- var pass = (typeof pass !== 'undefined')? pass : "";
- try {
- var resp = UrlFetchApp.fetch(url,
- (typeof user !== 'undefined')
- // if 'user' is set, pass 'headers' with auth stuff
- ?{'headers':
- {'Authorization': "Basic " + Utilities.base64Encode(user+':'+pass)},
- 'muteHttpExceptions': true
- }
- // else, don't pass any parameters
- :{}
- );
- } catch (e) {
- return [["#ERROR!", "could not open connection"],
- e.toString(),
- "response is: " + ((typeof resp === 'undefined')?'undefined':resp.toString())];
- }
- var connectionError = [];
- var headers = resp.getAllHeaders();
- var code; // report anything but success codes (HTTP 2XX):
- if ((code = resp.getResponseCode()) < 200 || code >= 300) {
- connectionError = [["#ERROR!"], ["server responded with code: ", code], "headers: "].concat(__formatHeaders(headers));
- }
- if (code == 401) { // specific additional info for 401 Unauthorized
- var headersHasBasicAuth = 0;
- if (typeof headers['WWW-Authenticate'] === 'string') {
- headersHasBasicAuth = headers['WWW-Authenticate'].match(/^Basic/) !== undefined;
- } else {
- Object.keys(headers['WWW-Authenticate']).reduce(function(a, val){
- return val.match(/^Basic/) !== undefined;
- }, 0);
- }
- if (headersHasBasicAuth) {
- connectionError[0].push("Server does not advertise Basic auth!");
- }
- }
- if (connectionError.length > 0) {
- return connectionError;
- }
- //Otherwise, the request was successful. Begin actually parsing XML:
- var xml = resp.getContentText();
- var document = XmlService.parse(xml);
- var root = document.getRootElement();
- var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom');
- var metadata = XmlService.getNamespace('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata')
- var entries = root.getChildren('entry', atom);
- var ret = []; // 2d array which we'll fill width-first; every dimension is a row
- for (var i = 0; i < entries.length; i++) {
- var content = entries[i].getChild('content', atom);
- var contentProperties = content.getChild('properties', metadata).getChildren();
- row = []
- for (var j = 0; j < contentProperties.length; j++) {
- /* wasteful way to populate an 'index' row, thus naming the columns.
- it requires you to change 'ret = []' to 'ret = [[]]' higher up.
- it'd be better (though maybe less readable) to do this in an
- earlier loop, but it's just here for debugging anyway. */
- // ret[0][j] = contentProperties[j].getName(); // wasteful, but easy to read
- row.push(contentProperties[j].getText());
- }
- ret.push(row);
- }
- return ret;
- }
- function __formatHeaders(rawHeaders) {
- /** Accepts a headers Object (from HTTPResponse.getAllHeaders()) and returns the
- headers, formatted as a 2d array that fits nicely in a spreadsheet. **/
- var names = Object.keys(rawHeaders);
- var headers2d = [];
- for (var i = 0; i < names.length; i++) {
- var row = [];
- row.push(names[i]);
- var header = rawHeaders[names[i]];
- if(typeof header === 'string') {
- row.push(header);
- } else {
- // header is an Object, not an Array, so we can't Array.prototype.concat()
- for (var j = 0; j < header.length; j++) {
- row.push(header[j]);
- }
- }
- headers2d.push(row);
- }
- // Transpose the array because it's sideways
- // Every row has to be the same length, so we'll pad them with null:
- var maxlen = headers2d.reduce(function(a, row) { if (row.length > a) return row.length; return a; }, 0);
- for (var i = 0; i < headers2d.length; i++) {
- while (headers2d[i].length < maxlen) {
- headers2d[i].push(null);
- }
- }
- // The actual transposition:
- headers2d = headers2d[0].map(function(col, i) { return headers2d.map(function(row) { return row[i]; } ); } );
- return headers2d;
- }
Advertisement
Add Comment
Please, Sign In to add comment