Filip Kuča
Filip Kuča

Reputation: 21

Parse XML file (which is stored on GoogleDrive) with Google app script

I have a few XML files stored on GoogleDrive. I would like to transfer data from XML file to Google spreadsheet with google apps script.

Is it possible parse XML file (which is stored on GoogleDrive) with Google apps script?

Upvotes: 2

Views: 2957

Answers (2)

bricoltou59
bricoltou59

Reputation: 74

I post a similar question here :

How to parse a XML file stored in my google drive but which stands out as a html type?

Maybe it can help you if i understand your situation: You have your xml files in google drive and not on extern sites.

First, If XmlFileonDrive is an object repredenting a xml file on your drive you can retrieve the fileId like this:

var fileId=XmlFileonDrive.getUrl().match(/https:\/\/drive.google.com\/file\/d\/(.*)\/view.*/)[1];

Then you could xmlParsing them like it work now for me :

var data = DriveApp.getFileById(fileId).getBlob().getDataAsString(); 
var xmlDocument=XmlService.parse(data);                              
var root=xmlDocument.getRootElement();
var mynamespace=root.getNamespace();
var titleTag=root.getChild("title",root.getNamespace()).getText();

Upvotes: 3

Mr.Rebot
Mr.Rebot

Reputation: 6791

First you must understand how to parse XML data, to get file using apps script. Unfortunately we can't directly get xml files in the google drive. It must be located outside google drive or in an eternal website. Refer to this site in using apps script parsing xml:

// Log the title and labels for the first page of blog posts on the Google Apps Developer blog.
function parseXml() {
  var url = 'http://googleappsdeveloper.blogspot.com/atom.xml';
  var xml = UrlFetchApp.fetch(url).getContentText();
  var document = XmlService.parse(xml);
  var root = document.getRootElement();
  var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom');

  var entries = document.getRootElement().getChildren('entry', atom);
  for (var i = 0; i < entries.length; i++) {
    var title = entries[i].getChild('title', atom).getText();
    var categoryElements = entries[i].getChildren('category', atom);
    var labels = [];
    for (var j = 0; j < categoryElements.length; j++) {
      labels.push(categoryElements[j].getAttribute('term').getValue());
    }
    Logger.log('%s (%s)', title, labels.join(', '));
  }
}

Then forward the values to the function that will create a spreadsheet. Here is another useful tutorial.

Upvotes: 0

Related Questions