il_mix
il_mix

Reputation: 581

Update an XML file in Google Drive via Google API

Let's say I have this minimal XML file on Google Drive.

<?xml version="1.0" encoding="UTF-8"?>
<MyCounter>
  <counter>137</counter>
</MyCounter>

Using Google Script, I want to:

  1. parse the XML
  2. add 1 to the counter
  3. update the file.

I'm at step 2 at the moment. I can delete the old file and create a new one with the same name and updated content. I prefer to update the existing one instead, so it will maintain the unique ID, and I can access the file with said ID instead of searching for it via file name.

Upvotes: 1

Views: 601

Answers (1)

Tanaike
Tanaike

Reputation: 201513

  • You want to update a text file in your Google Drive without changing the file ID.
  • You want to add 1 to 137 of <counter>137</counter> in the file.
  • You want to achieve above using Google Apps Script.

If my understanding is correct, how about this sample script? I think that there are several answers for your situation. So please think of this as just one of them.

Flow:

  1. Retrieve data from the text file.
  2. Add 1 to number of <counter>{number}</counter> using replace().
  3. Update the file using setContent().

By this flow, the file can be updated without changing file ID.

Sample script:

var fileId = "#####"; // Please set fileId here.
var file = DriveApp.getFileById(fileId);
var str = file.getBlob().getDataAsString();
var r = str.replace(/<counter>(\d+)<\/counter>/, function(_, p) {
  return "<counter>" + (Number(p) + 1) + "</counter>";
});
file.setContent(r);

Note:

  • If you have already prepared the script for adding the counter, please use it.

References:

Upvotes: 1

Related Questions