GASでXML(RSS)を取得して処理する

ossanfmのRSS feedを取得するコード

const ns_itunes = XmlService.getNamespace("itunes","http://www.itunes.com/dtds/podcast-1.0.dtd");

const response = UrlFetchApp.fetch('https://ossan.fm/feed.xml');
const xml = XmlService.parse(response.getContentText());

const root = xml.getRootElement();
const channel = root.getChild('channel');

const podcastName = channel.getChild('title').getText(); 

// channelの下のitem群を取得
channel.getChildren('item').forEach((item,i) => {
    let title = item.getChild("title").getText();
    let link = item.getChild("link").getText();
    let enclosure = item.getChild("enclosure").getAttribute("url").getValue(); //属性値を取得
    let duration = item.getChild("duration",ns_itunes).getText(); // itunes:duration タグを処理
    let date = Utilities.formatDate(new Date(item.getChild("pubDate").getText()), 'Asia/Tokyo', 'yyyy/MM/dd');//日付の処理
    console.log(title,link,date,enclosure,duration);
})

メモ

  • 外部のRSSを取得
    • UrlFetchApp.fetch(url)を利用する
  • XMLをparse
    • XmlService.parse(text)を利用する
  • タグの値を取得
    • Element.getChild(tagname).getText() を利用する
  • 属性値を取得
    • getAttribute(attributeName)を利用する
  • 特殊な名前空間のタグを取得
    • XmlService.getNamespace(prefix, uri) / Element.getChild(tagname, namespace) を利用
    • itunes:durationの場合
      • prefixにitunesを指定、getChildのtagnameにはdurationを指定