如何在Google Apps Script中终止foreach循环 仅用首个RSS条目生成DOC
实现方案
你当前使用的forEach循环本身不支持主动终止,会遍历所有返回的RSS条目,才会出现生成重复文档的问题。要实现仅处理第一条条目后停止,最简单高效的方式是直接获取条目列表的第一个元素,无需遍历:
function myFunction1() { const url = "https://cdn.feedcontrol.net/1830/2857-8L5Ntr0N5l5Xf.xml"; const data = UrlFetchApp.fetch(url).getContentText(); const root = XmlService.parse(data).getRootElement(); const ns1 = root.getNamespace(); const ns2 = XmlService.getNamespace("http://purl.org/rss/1.0/modules/content/"); // 获取所有条目列表 const items = root.getChild("channel", ns1).getChildren("item", ns1); // 非空判断,避免RSS无条目时脚本报错 if (items.length > 0) { const firstItem = items[0]; Drive.Files.insert({ title: firstItem.getChild("title", ns1).getValue(), mimeType: MimeType.GOOGLE_DOCS }, HtmlService.createHtmlOutput(firstItem.getChild("encoded", ns2).getValue()).getBlob()); } }
如果你后续需要处理前N条新增内容(比如你提到的5条新内容),可以用普通for循环控制处理数量,示例如下:
function myFunction1() { const url = "https://cdn.feedcontrol.net/1830/2857-8L5Ntr0N5l5Xf.xml"; const data = UrlFetchApp.fetch(url).getContentText(); const root = XmlService.parse(data).getRootElement(); const ns1 = root.getNamespace(); const ns2 = XmlService.getNamespace("http://purl.org/rss/1.0/modules/content/"); const items = root.getChild("channel", ns1).getChildren("item", ns1); // 取条目数和5的最小值,避免条目不足5条时报错 const processNum = Math.min(5, items.length); for (let i = 0; i < processNum; i++) { const item = items[i]; Drive.Files.insert({ title: item.getChild("title", ns1).getValue(), mimeType: MimeType.GOOGLE_DOCS }, HtmlService.createHtmlOutput(item.getChild("encoded", ns2).getValue()).getBlob()); } }
内容的提问来源于stack exchange,提问作者Hạnh Khánh
相关产品推荐
相关产品推荐

