GoogleスプレッドシートテーブルからXMLフィードを作成しようとしています

Aug 19 2020

助けを求めて、私は今ほとんど一日中コードをいじくり回していて行き詰まっていて、これは私がこれまでに見つけた最良の解決策のようです。

Googleスプレッドシートの表からXMLファイルを作成するスクリプトを作成しようとしています。

サンプルシートはこんな感じです>> https://docs.google.com/spreadsheets/d/1tSWMiXBRyhFcAmwpH5tEJiyHCB5vjlGwuHFv865-85A/edit?usp=sharing

このコード例のGoogleScript Export Spreadsheet to XML Fileに出くわしましたが、これは必要なものの90%であり、ここでWebアプリとして公開することで機能しました>>https://script.google.com/macros/s/AKfycbxVcUi6dXw0D1CWfZTlwf94gAT9QjqpG__-SaCIHVFVPzftndU/exec?id=1tSWMiXBRyhFcAmwpH5tEJiyHCB5vjlGwuHFv865-85A

XMLをフォーマットする必要があるため、ヘッダーと値をループすることに固執しています。

また、いくつかの値に属性があるので、以下の例の10 AM:6PMにxml:lang = "x-default"を追加するのは難しいと思います。

これは私が作成しようとしているものの例です

<store store-id="F123">
    <name>Store One</name>
    <address1>123 Street</address1>
    <address2></address2>
    <city>London</city>
    <postal-code>L67 9JF</postal-code>
    <phone>123 456</phone>
    <store-hours xml:lang="x-default">10AM | 6PM</store-hours>
    <custom-attribute attribute-id="freeTextTitle" xml:lang="x-default">Store Description Title</custom-attribute>
    <custom-attribute attribute-id="v3_store_open_hours_0" xml:lang="x-default">11 AM|7 PM</custom-attribute>
</store>
<store store-id="G456">
    <name>Store Two</name>
    <address1>123 Street</address1>
    <address2></address2>
    <city>Manchester</city>
    <postal-code>L67 9DS</postal-code>
    <phone>123 456</phone>
    <store-hours xml:lang="x-default">10AM | 6PM</store-hours>
    <custom-attribute attribute-id="freeTextTitle" xml:lang="x-default">Store Description Title</custom-attribute>
    <custom-attribute attribute-id="v3_store_open_hours_0" xml:lang="x-default">11 AM|7 PM</custom-attribute>
</store>

どうもありがとう

**より多くのコンテキストを追加しました

おかげで、両方、私は実際にヘッダーと属性をマップしようとしているdoIt関数のJavaScript map()関数で立ち往生しています

function doGet(e) {
  var content;
  try {
    content = doIt(e);
  } catch(err) {
    content = '<error>' + (err.message || err) + '</error>';
  }
  return ContentService.createTextOutput(content).setMimeType(ContentService.MimeType.XML);
}

function doIt(e) {
  if (!e) throw 'you cannot run/debug this directly\nyou have to either call the url or mock a call';
  if (!e.parameter.id) throw '"id" parameter not informed. Please provide a spreadsheet id.';

  var values = SpreadsheetApp.openById(e.parameter.id).getSheets()[0].getRange('A1:J4').getValues();
  return '<sheet>' + values.map(function(row, i) {
    return '<row>' + row.map(function(v) {
      return '<cell>' + v + '</cell>';
    }).join('') + '</row>';
  }).join('') + '</sheet>';
}

値は範囲内のすべての値を取得しますが、値を分解しようとすると少し迷います。

map()関数でいくつかの読み取りを行ったので、もう一度やり直してください

回答

2 Tanaike Aug 19 2020 at 15:35

簡単な変更として、次の変更はどうですか?

スクリプトで<sheet>は、、、<row>および<cell>タグが使用されます。しかし、これらはあなたの期待する結果に含まれていないようです。1行目のヘッダー行を各タグとして使用する場合は、スクリプトで使用する必要があります。スクリプトを変更すると、次のようになります。

変更されたスクリプト:

この変更では、doIt()が変更されました。

function doIt(e) {
  if (!e) throw 'you cannot run/debug this directly\nyou have to either call the url or mock a call';
  if (!e.parameter.id) throw '"id" parameter not informed. Please provide a spreadsheet id.';
  var values = SpreadsheetApp.openById(e.parameter.id).getSheets()[0].getRange('A1:J4').getValues();

  // I modified below script.
  var header = values.shift();
  return values.reduce((s, r) => {
    r.forEach((c, j, a) => {
      s += j == 0 ? `<${header[j]}="${c}">` : `<${header[j]}>${c}<\/${header[j].split(" ")[0]}>`; if (j == a.length - 1) s += `<\/${header[0].split(" ")[0]}>`;
    });
    return s;
  }, "");
}

結果:

上記の変更したスクリプトを実行すると、次の結果が得られます。

<store store-id="F123">
   <name>Store One</name>
   <address1>123 Street</address1>
   <address2 />
   <city>London</city>
   <postal-code>L67 9JF</postal-code>
   <phone>123 456</phone>
   <store-hours xml:lang="x-default">10AM | 6PM</store-hours>
   <custom-attribute attribute-id="freeTextTitle" xml:lang="x-default">Store Description Title</custom-attribute>
   <custom-attribute attribute-id="v3_store_open_hours_0" xml:lang="x-default">11 AM|7 PM</custom-attribute>
</store>
<store store-id="G456">
   <name>Store Two</name>
   <address1>124 Street</address1>
   <address2 />
   <city>Manchester</city>
   <postal-code>L67 9DS</postal-code>
   <phone>124 111</phone>
   <store-hours xml:lang="x-default">9AM | 5PM</store-hours>
   <custom-attribute attribute-id="freeTextTitle" xml:lang="x-default">Store Description Title</custom-attribute>
   <custom-attribute attribute-id="v3_store_open_hours_0" xml:lang="x-default">12 AM|7 PM</custom-attribute>
</store>
<store store-id="J542">
   <name>Store Three</name>
   <address1>777 High Street</address1>
   <address2 />
   <city>Leeds</city>
   <postal-code>L7 9GG</postal-code>
   <phone>555 222</phone>
   <store-hours xml:lang="x-default">10AM | 6PM</store-hours>
   <custom-attribute attribute-id="freeTextTitle" xml:lang="x-default">Store Description Title</custom-attribute>
   <custom-attribute attribute-id="v3_store_open_hours_0" xml:lang="x-default">12 AM|7 PM</custom-attribute>
</store>

注意:

  • たとえば、上記の結果をxmlデータとして使用する場合は、のように囲む必要があると思います<contents>{above results}</contents>。これに注意してください。したがって、有効なXMLデータをエクスポートする場合は、次のスクリプトを使用してください。この場合、<contents>はサンプルタグです。

      function doIt(e) {
        if (!e) throw 'you cannot run/debug this directly\nyou have to either call the url or mock a call';
        if (!e.parameter.id) throw '"id" parameter not informed. Please provide a spreadsheet id.';
        var values = SpreadsheetApp.openById(e.parameter.id).getSheets()[0].getRange('A1:J4').getValues();
    
        // I modified below script.
        var header = values.shift();
        var data = values.reduce((s, r) => {
          r.forEach((c, j, a) => {
            s += j == 0 ? `<${header[j]}="${c}">` : `<${header[j]}>${c}<\/${header[j].split(" ")[0]}>`; if (j == a.length - 1) s += `<\/${header[0].split(" ")[0]}>`;
          });
          return s;
        }, "");
    
        return XmlService.getPrettyFormat().format(XmlService.parse(`<contents>${data}$</contents>`));
      }
    
  • Web Appsのスクリプトを変更した場合は、WebAppsを新しいバージョンとして再デプロイしてください。これにより、最新のスクリプトがWebアプリに反映されます。これに注意してください。

  • このスクリプトは、V8を有効にして使用してください。

参照:

  • reduce()
  • forEach()